您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關JavaWeb如何使用mvc模式實現登錄功能的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
1.導包
2.web >> index.jsp web >> login.jsp web >> success.jsp
1) web >> index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="login.jsp">登錄</a> </body> </html>
2) web >> login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> <style> #msg { color: red; } </style> </head> <body> <form action="user" method="post"> 賬號:<input type="text" name="userName"><span id="msg"><%=request.getAttribute("msg")%></span> 密碼:<input type="text" name="passWord"> <input type="hidden" name="method" value="login"> <input type="submit" value="登錄"> </form> </body> </html>
3) web >> success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="constant.Con" %> <html> <head> <title>用戶中心</title> </head> <body> <%=request.getSession().getAttribute(Con.USER)%><h2 >歡迎您</h2> <a href="login.html">返回重新登錄</a> </body> </html>
3.constant >> Con
package constant; import java.io.Serializable; public class Con implements Serializable { //session中保存用戶登錄信息 public static final String USER = "user"; }
entity >> User
package entity; import java.io.Serializable; public class User implements Serializable { private int id; private String userName; private String passWord; public User(int id, String userName, String passWord) { this.id = id; this.userName = userName; this.passWord = passWord; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } }
4.resources >> prop.properties
driverClassName=com.mysql.cj.jdbc.Driver urlName=jdbc:mysql://localhost:3306/myjdbc?characterEncoding=utf8&useSSL=false&serverTimezone=UTC userName=root passwordName=root
5.utils >> JDBCUtils
package utils; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; /* JDBC工具類 */ public class JDBCUtils { // 聲明驅動的路徑 static String driverClass; static String url; static String user; static String password; /* 靜態代碼塊只會在加載class文件的時候執行一次, 將注冊驅動的代碼由靜態代碼塊來實現 */ static { // 創建屬性集對象 Properties prop = new Properties(); // 將文件中的數據讀取到屬性集中 try { //prop.properties InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("prop.properties"); prop.load(is); } catch (IOException e) { e.printStackTrace(); } // 獲取key對應的value driverClass = prop.getProperty("driverClassName"); url = prop.getProperty("urlName"); user = prop.getProperty("userName"); password = prop.getProperty("passwordName"); try { // 加載驅動 Class.forName(driverClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /* 將獲取資源的方法進行封裝: Connection連接接口對象 */ public static Connection getConnection() throws SQLException, ClassNotFoundException { // 獲取連接 Connection connection = DriverManager.getConnection(url, user, password); return connection; } /* 封裝方法,用于釋放資源 */ public static void close(Connection connection, Statement statement, ResultSet resultSet) { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { e.printStackTrace(); } // 調用已經實現功能的方法直接使用 close(connection, statement); } /* 重載一個釋放資源的代碼,用來釋放兩個資源 */ public static void close(Connection connection, Statement statement) { try { if (statement != null) { statement.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
6.servlet >> UserServlet
package servlet; import constant.Con; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "user", urlPatterns = "/user") public class UserServlet extends HttpServlet { private UserService userService = new UserServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.設置請求字符集為utf-8 req.setCharacterEncoding("utf-8"); //2.獲取請求參數method,根據值調用不同方法處理業務 String method = req.getParameter("method"); if (method.equals("login")) { this.login(req, resp); } } //登錄方法 private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.獲取賬號和密碼 String userName = req.getParameter("userName"); String passWord = req.getParameter("passWord"); //2.調用service的方法處理登錄 boolean result = userService.checkUser(userName, passWord); if (result) { //true表示登錄成功 //轉發跳轉成功頁面 //req.getRequestDispatcher("/success.jsp").forward(req, resp); //將用戶信息保存在session域對象中 req.getSession().setAttribute(Con.USER, userName); //重定向跳轉成功頁面 resp.sendRedirect(req.getContextPath() + "/success.jsp"); } else { //false登錄失敗,返回登錄頁面 req.setAttribute("msg", "賬號密碼不匹配"); req.getRequestDispatcher("/login.jsp").forward(req, resp); } } }
7.service >> UserService service >> impl >> UserServiceImpl
package service; public interface UserService { //判斷登錄成功與否 boolean checkUser(String userName, String passWord); }
package service.impl; import dao.UserDao; import dao.impl.UserDaoImpl; import entity.User; import service.UserService; import utils.JDBCUtils; import java.sql.Connection; import java.util.List; public class UserServiceImpl implements UserService { private UserDao userDao = new UserDaoImpl(); @Override public boolean checkUser(String userName, String passWord) { // 連接對象 Connection connection = null; try { //1.獲取數據庫連接 connection = JDBCUtils.getConnection(); //2.調用dao方法查詢數據 List<User> users = userDao.findUserByUserNameAndPassWord(connection, userName, passWord); //3.根據查詢結果返回成功失敗標志 if (users.size() > 0) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } finally { JDBCUtils.close(connection, null); } } }
8.dao >> UserDao dao >> impl >> UserDaoImpl
package dao; import entity.User; import java.sql.Connection; import java.util.List; public interface UserDao { //根據賬號密碼查詢數據庫,返回結果集 List<User> findUserByUserNameAndPassWord(Connection connection, String userName, String passWord); }
package dao.impl; import dao.UserDao; import entity.User; import utils.JDBCUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class UserDaoImpl implements UserDao { @Override public List<User> findUserByUserNameAndPassWord(Connection connection, String userName, String passWord) { // 發送sql語句對象 PreparedStatement statement = null; List<User> userList = new ArrayList<>(); try { connection = JDBCUtils.getConnection(); // 獲取Statement對象 statement = connection.prepareStatement("select * from user where username = ? and password = ?"); statement.setString(1, userName); statement.setString(2, passWord); ResultSet rs = statement.executeQuery(); while (rs.next()) { User user = new User(); int id = rs.getInt(1); String username = rs.getString(2); String password = rs.getString(3); user.setId(id); user.setUserName(username); user.setPassWord(password); userList.add(user); } return userList; } catch (Exception e) { e.printStackTrace(); return userList; } finally { JDBCUtils.close(null, statement, null); } } }
1.首頁 index.jsp
2.錯誤登錄 login.jsp
3. 正確登錄 login.jsp
4. 登錄成功 success.jsp
感謝各位的閱讀!關于“JavaWeb如何使用mvc模式實現登錄功能”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。