[Filter] 網頁自動登錄


網頁自動登錄

1. 主要需求

  1. 編寫首頁,檢查用戶是否登陸;
  2. 編寫 login.jsp;
  3. 編寫 LoginServlet;
  4. 編寫過濾器讀取 Cookie 的信息。

2. 代碼實現

a. 實體類

package com.company;

public class User {

    private String userName;

    private String paasword;

    public User(String userName, String paasword) {
        this.userName = userName;
        this.paasword = paasword;
    }

    public User() {
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPaasword() {
        return paasword;
    }

    public void setPaasword(String paasword) {
        this.paasword = paasword;
    }
}

b. 首頁 demo.jsp

  • 檢查服務器端的 Session,如果 Session 中有成功登錄的數據則自動登錄。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>demo.jsp</title>
</head>
<body>
<c:choose>
    <%--注意:如果登陸成功,Session會存儲一個登錄成功的信息,名字爲loginUser;--%>
    <c:when test="${loginUser!=null}">
        <%--已經登錄--%>
        <h4>歡迎:${loginUser.userName}</h4>
    </c:when>
    <c:otherwise>
        <a href="${pageContext.request.contextPath}/login.jsp">登錄</a>
    </c:otherwise>
</c:choose>

<h2>商品列表</h2>
</body>
</html>

c. 登錄頁 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login.jsp</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/loginServlet" method="post">
    用戶名:<input type="text" name="userName"/><br/>
    密碼:<input type="password" name="password"/><br/>
    七天免登陸<input type="checkbox" name="auto" value="true"/>
    <input type="submit" value="登陸"/>
</form>
</body>
</html>

d. 確認登錄頁信息 LoginServlet

  • 匹配數據庫(此處直接替換爲明文)中的用戶數據與登錄頁中上傳的用戶數據,並在 Session 中保存成功登陸的數據。
  • 通過設定 Cookie 的生命週期,來確定瀏覽器端用戶信息是否可以自動登錄。
package com.company;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 獲取用戶名與密碼
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        //2. 校驗用戶名與密碼
        if (userName.equals("Regino") && password.equals("123")) {
            //正確用戶名與密碼
            //3. 檢查是否要七天免登陸
            String auto = request.getParameter("auto");//如果複選框被選中,那麼該值就不爲null
            if (auto == null) {
                //4. 用戶不需要七天免登錄, 清楚以前Cookie信息
                Cookie cookie = new Cookie("autoLogin", "");
                cookie.setMaxAge(0);
                response.addCookie(cookie);

            } else {
                //5.用戶需要七天免登錄, 用戶名與密碼已經保存到Cookie中
                Cookie cookie = new Cookie("autoLogin", userName + "_" + password);
                cookie.setMaxAge(60 * 60 * 24 * 7); //七天
                response.addCookie(cookie);
            }

            //6.不管是否要七天免登錄,那麼登陸成功我們都需要在Session中做一個登陸成功標記
            request.getSession().setAttribute("loginUser", new User(userName, password));
            //跳轉到首頁
            response.sendRedirect(request.getContextPath() + "/demo.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

e. 確認登錄頁信息的過濾器 AutoLoginFilter

  • 即把 Cookie 讀取到 Session 中。
  • 過濾器讀取 Cookie 的數據,在確認登錄頁信息前,檢查 Session 中是否存有 Cookie 中的數據,如果沒有且 Cookie 中的數據正確,則將數據保存到 Session 中。
package com.company;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        /*
        HttpServletRequest是屬於ServletRequest的子接口, 所以HttpServletRequest的方法肯定要比ServletRequest的要多。
        這裏的強制類型轉換的目的就是爲了使用子接口的方法,之所以可以強制類型轉換是因爲Tomcat本身傳遞過來的就是HttpServletRequest。
        */
        //1. 檢查用戶是否在Session有登錄成功標記
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            //2. 如果用戶還沒有登錄,那麼就讀取Cookie的信息
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                //遍歷所有的Cookie,找到AutoLogin的Cookie
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("autoLogin")) {
                        //獲取用戶名與密碼
                        String[] arrayInfo = cookie.getValue().split("_"); //Regino_123
                        String userName = arrayInfo[0];
                        String pasword = arrayInfo[1];
                        if (userName.equals("Regino") && pasword.equals("123")) {
                            //登錄成功
                            session.setAttribute("loginUser", new User(userName, pasword));
                        }
                    }
                }
            }
        }
        //不管用戶是否已經登陸,都需要放行
        chain.doFilter(request, resp);
    }

    public void destroy() {

    }
}

3. 測試


  • 點擊登錄跳轉頁面,輸入用戶名和密碼,並確認免登錄:
    在這裏插入圖片描述


  • 如果未選定免登錄,重新部署或關閉 Tomcat 後,頁面提示需要再次登錄:
    在這裏插入圖片描述

原文鏈接:https://qwert.blog.csdn.net/article/details/105756432

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章