1. 程式人生 > 程式設計 >JavaWeb使用mvc模式實現登入功能

JavaWeb使用mvc模式實現登入功能

目錄
  • 部署專案、環境搭建
  • 詳細內容
  • 登入實現

部署專案、環境搭建

JavaWeb使用mvc模式實現登入功能

JavaWeb使用mvc模式實現登入功能

詳細內容

1.導包

JavaWeb使用mvc模式實現登入功能

2.web >> index.p web >> login.jsp web >>success.jsp

JavaWeb使用mvc模式實現登入功能

1) web >> index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="" %>
<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)%><h1 style="color: green">歡迎您</h1>
<a href="login.html">返回重新登入</a>
</body>
</html>http://www.cppcns.com
;

3.constant >> Con

JavaWeb使用mvc模式實現登入功能

package constant;
 
import java.io.Serializable;
 
public class Con implements Serializable {
    //session中儲存使用者登入資訊
    public static final String USER = "user";
}

entity >> User

JavaWeb使用mvc模式實現登入功能

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

JavaWeb使用mvc模式實現登入功能

driverClassName=com..cj.jdbc.Driver
urlName=jdbc:mysql://localhost:3306/myjdbc?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
userName=root
passwordName=root

JavaWeb使用mvc模式實現登入功能

5.utils >> JDBCUtils

JavaWeb使用mvc模式實現登入功能

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

JavaWeb使用mvc模式實現登入功能

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,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 >> UserServiceservice >> impl >> UserServiceImpl

JavaWeb使用mvc模式實現登入功能

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

JavaWeb使用mvc模式實現登入功能

package dao;
 
import entity.User;
import java.sql.Connection;
import java.util.List;
 
public interface UserDao {
    //根據賬號密碼查詢資料庫,返回結果集
    List<User> findUserByUserNameAndPassWord(Connection connection,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 userNamVTMQwWDe,String passWord) {
        // 傳送sql語句物件
        PreparedStatement statement = null;
        List&lVTMQwWDt;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

JavaWeb使用mvc模式實現登入功能

2.錯誤登入login.jsp

JavaWeb使用mvc模式實現登入功能

JavaWeb使用mvc模式實現登入功能

3. 正確登入login.jsp

JavaWeb使用mvc模式實現登入功能

4. 登入成功success.jsp

JavaWeb使用mvc模式實現登入功能

到此這篇關於JavaWeb使用mvc模式實現登入功能的文章就介紹到這了,更多相關JavaWeb mvc登入內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!