Introduction to the

SpringMVC’s processor interceptor is similar to the Filter used in Servlet development for pre-processing and post-processing of the processor. Developers can define their own interceptors to implement specific functions.

The filter

  1. Part of the Servlet specification that can be used by any Java Web project
  2. After /* is configured in url-pattern, all resources to be accessed can be intercepted

The interceptor

  1. Interceptors are the SpringMVC framework’s own and can only be used by projects that use the SpringMVC framework
  2. The interceptor only intercepts the controller method being accessed, not JSP/HTML/CSS /image/js

The difference between filters and interceptors:

Interceptors are concrete applications of AOP ideas.

Initial experience with interceptor

  1. Create a new project, add Web support, and import the lib package that the project depends on in IDEA.
  2. Configure web. XML

      
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>


</web-app>
Copy the code
  1. Configuration for springmvc – servlet. XML

      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <! -- Scan the specified package to validate the annotations under the specified package -->
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>

    <! JSON -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <! -- View resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

Copy the code
  1. Write a custom interceptor. (Implementation of HandlerInterceptor interface)
package 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 MyInterceptor implements HandlerInterceptor {

    // execute before the request processing method
    // Execute the next interceptor if true is returned
    // The next interceptor is not executed if false is returned
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------ before processing ------------");
        return true;
    }
    // execute after the request handler is executed
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("------------ after processing ------------");
    }
    // Perform cleanup after dispatcherServlet processing.
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- to clean up -- -- -- -- -- -- -- -- -- -- -- --"); }}Copy the code

In fact, simply override the preHandle method.

  1. Configure interceptors in the SpringMVC-servlet.xml file
    <! -- Interceptor configuration -->
    <mvc:interceptors>
        <mvc:interceptor>
            <! --/** includes paths and their subpaths -->
            <! /admin/add/user /admin/add/user
            <! --/admin/** intercepts all files under /admin/
            <mvc:mapping path="/ * *"/>
            <! The interceptor is configured for the bean.
            <bean class="interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
Copy the code
  1. Writing the controller
package controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class InterceptorController {
    @RequestMapping("/interceptor")
    public String test(a){
        System.out.println("InterceptorController");
        return "ok"; }}Copy the code
  1. Configure Tomcat and test it

First taste: The custom interceptor implements the HandlerInterceptor interface and overrides the preHandle method. In the preHandle method, the return value determines whether to intercept. When the return value is true, no intercept is performed. Otherwise intercept.

  1. Results:
    • Return true, interceptor does not intercept, jump
    • Return false, interceptor intercepts, does not jump

Interceptor Reexperience – Login authentication

Implementation approach

  1. There is a login page, and you need to write a Controller access page.
  2. The landing page has an action to submit the form. It needs to be handled in the controller. Check whether the user name and password are correct. If correct, write user information to session. Return landing successful.
  3. Intercept user requests to determine whether the user is logged in. If the user is logged in. If the user does not log in, the login page is displayed

Login screen

<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> title </title> </head> <h1> Login page </h1> <hr> <body> <form action="${pageContext.request.contextPath}/user/login"> User name: <input type="text" name="username"> <br> Password: <input type="password" name="pwd"> <br>
   <input type="submit" value="Submit">
</form>
</body>
</html>
Copy the code

Controller handles requests

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

   // Jump to the login page
   @RequestMapping("/jumplogin")
   public String jumpLogin(a) throws Exception {
       return "login";
  }

   // Go to the success page
   @RequestMapping("/jumpSuccess")
   public String jumpSuccess(a) throws Exception {
       return "success";
  }

   // Login and submit
   @RequestMapping("/login")
   public String login(HttpSession session, String username, String pwd) throws Exception {
       // Records user identity information to the session
       System.out.println("Receiving front end ==="+username);
       session.setAttribute("user", username);
       return "success";
  }

   // Log out
   @RequestMapping("logout")
   public String logout(HttpSession session) throws Exception {
       / / the session has expired
       session.invalidate();
       return "login"; }}Copy the code

Login success page

<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > title < / title > < / head > < body > < h1 > login success page < / h1 > < hr > ${user} < a href ="${pageContext.request.contextPath}/user/logout"> Log off </a> </body> </ HTML >Copy the code

The index page

<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > $title $< / title > < / head > < body > < h1 > home page < / h1 > < hr > < % - login - % > < a href ="${pageContext.request.contextPath}/user/jumplogin"> login </a> <a href="${pageContext.request.contextPath}/user/jumpSuccess"> Success page </a> </body> </ HTML >Copy the code

Writing controller

package interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

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

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().contains("login")) {
            return true;
        }

        HttpSession session = request.getSession();

        // If the user is logged in, do not intercept
        if(session.getAttribute("user") != null) {
            return true;
        }

        // The user is not logged in, blocked, and redirected to the login page
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false; }}Copy the code

Configure interceptors in SpringMVC-servlet.xml

<mvc:interceptor>
            <mvc:mapping path="/ * *"/>
            <bean id="loginInterceptor" class="interceptor.LoginInterceptor"/>
        </mvc:interceptor>
Copy the code

Configure Tomcat and test it.

Result: Without login, you cannot directly access the successful login page.