SpringMVC自定義攔截器登錄檢測功能的實現代碼

一、定義登錄控制器

目錄結構

在這裡插入圖片描述

代碼:

1、創建TUser類

package com.demo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TUser {
    private String name;
    private String password;
}

2、創建LoginController類

package com.demo.controller;

import com.demo.pojo.TUser;
import com.demo.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {
    @RequestMapping("/login")
    public String login(Model model){
        model.addAttribute("msg","這裡是登陸界面");
        return "login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(TUser tUser,
                          HttpServletRequest req, HttpServletResponse resp, Model model){
        System.out.println("###LoginController.doLogin()");

        if(!"admin".equals(tUser.getName())||!"admin".equals(tUser.getPassword())){
            model.addAttribute("msg","用戶名或密碼不正確!");
            return "loginFail";//跳轉到loginFail.jsp
        }

        HttpSession httpSession=req.getSession(true);//存在session則使用,不存在則創建
        httpSession.setAttribute("user",tUser);
        model.addAttribute("msg","登錄成功");
        return "success";//跳轉到success.jsp
    }

    @RequestMapping("/loginOut")
    public String loginFail(HttpSession session,Model model){
        model.addAttribute("msg","退出登錄");
        session.removeAttribute("user");
        return "login";
    }

}

頁面代碼:

1、login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<h1>${msg}</h1>
<form id="login" action="${pageContext.request.contextPath}/user/doLogin" method="post">
    用戶名:<input type="text" name="name"/><br/>
    密碼:<input type="password" name="password"><br/>
    <input type="submit">
</form>

</body>
</html>

2、loginFail.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>loginFail</title>
</head>
<body>
<h1>${msg}</h1>
<h2><a href="${pageContext.request.contextPath}/user/loginOut" rel="external nofollow"  rel="external nofollow" >返回登錄界面</a></h2>
</body>
</html>

3、success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
${msg}
<h2><a href="${pageContext.request.contextPath}/user/loginOut" rel="external nofollow"  rel="external nofollow" >退出登錄</a></h2>
</body>
</html>

二、自定義登錄攔截器

代碼:

1、創建LoginInterceptor類,作為攔截器類需實現HandlerInterceptor,並重寫裡面的三個方法preHandle、postHandle、afterCompletion:

package com.demo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("LoginInterceptor preHandle");
        //放行:判斷什麼情況下
        //1、請求到登陸界面放行,首次登陸
        if(request.getRequestURI().contains("login")||request.getRequestURI().contains("doLogin")){
            return true;
        }
        //2、退出登錄可直接放行
        if(request.getRequestURI().contains("loginOut")){
            return true;
        }
        //3、通過登錄進入 放行
        if(request.getSession().getAttribute("user")!=null){
            return true;
        }
        //非法請求進行攔截
        //重定向到登錄頁面
        response.sendRedirect(request.getContextPath()+"login");
        //攔截
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor  "+"postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        System.out.println("LoginInterceptor  "+"afterCompletion");
    }
}

2、在spring-mvc.xml中配置LoginInterceptor攔截器 測試: 1、正常登錄(正確密碼:admin)

在這裡插入圖片描述

1.1、點擊退出登錄

在這裡插入圖片描述

2、用戶名密碼錯誤

在這裡插入圖片描述

2.1、點擊返回登錄界面

在這裡插入圖片描述

3、非法請求

在這裡插入圖片描述

到此這篇關於SpringMVC自定義攔截器登錄檢測功能的實現的文章就介紹到這瞭,更多相關SpringMVC自定義攔截器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: