Introduction to the

Similar to the Filter in Servlet development, it is a concrete application of AOP ideas.

Only access controller methods are blocked, not JSP/HTML/CSS /image/js

Custom interceptors

Configure the corresponding web. XML, Spring configuration file

1. HandlerInterceptor inheritance

The HandlerInterceptor implements these three methods by default and does not override them

public class MyInterceptor implements HandlerInterceptor {
    //false does not allow the next interceptor to proceed, stuck in the current method
    //true allows the next interceptor to proceed
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------- before interception -----------");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("------------- after intercept -----------");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- to clean up -- -- -- -- -- -- -- -- -- -- -"); }}Copy the code

Configure the Spring configuration file

 <mvc:interceptors>
        <mvc:interceptor>
        <! --/** Intercepts all files in the current directory including its subdirectories /* Intercepts only files in the current directory such as /a/* Intercepts only /a/b but not /a/b/c-->
            <mvc:mapping path="/ * *"/>
         <! -- Specify the interceptor we are using -->   
            <bean class="config.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
Copy the code

Controller

@Controller
public class MyController {
    @RequestMapping("/t")
    @ResponseBody
    public String test(a){
        System.out.println("test is start");
        return "test is ok "; }}Copy the code

The execution result

-- -- -- -- -- -- -- -- -- -- -- -- -- before -- -- -- -- -- -- -- -- -- -- - the test is start -- -- -- -- -- -- -- -- -- -- -- -- -- to intercept after -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - clean up -- -- -- -- -- -- -- -- -- -- -Copy the code

Practice – Login interception

Custom interceptors

package config;

import org.springframework.web.servlet.HandlerInterceptor;

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

public class LogInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // If the login page is displayed, the system permits the login
        if (request.getRequestURI().contains("login")){
            System.out.println("contains---login");
            return true;
        }
        // If you have logged in, permit
        if (request.getSession().getAttribute("name")! =null&&!"".equals(request.getSession().getAttribute("name")))
        {
            System.out.println("name:---------"+request.getSession().getAttribute("name"));
            return true;
        }
        // Otherwise, return to the login page
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false; }}Copy the code

Configure the spring

<mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <bean class="config.LogInterceptor"/>
        </mvc:interceptor>
Copy the code

The front-end interface

The initial interface

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2021/3/21
  Time: 15:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/user/gologin"> login </a> <a href="${pageContext.request.contextPath}/user/main"> Home </a> </body> </ HTML >Copy the code

Login screen

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2021/3/21
  Time: 16:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    <input type="text" name="name">
    <input type="password" name="pwd">
    <input type="submit">
</form>


</body>
</html>

Copy the code

Home page

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2021/3/21
  Time: 16:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java"% ><html>
<head>
    <title>Title</title>
</head>
<body>Homepage ${name}<a href="${pageContext.request.contextPath}/user/goOut">The cancellation</a>
</body>
</html>

Copy the code

Controller

package controller;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class MyController {
    @RequestMapping("/main")
    public String main(a){
        return "main";
    }
    @RequestMapping("/gologin")
    public String gologin(a){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String name, String pwd, HttpSession httpSession){
        httpSession.setAttribute("name",name);
        httpSession.setAttribute("pwd",pwd);
        return "main";
    }
    @RequestMapping("/goOut")
    public String goOut(HttpSession httpSession){
        httpSession.removeAttribute("name");
        httpSession.removeAttribute("pwd");
        httpSession.invalidate();
        return "login"; }}Copy the code