Spring MVC learning notes - interceptor

Posted by jbrave on Sun, 23 Jan 2022 09:56:25 +0100

Spring MVC learning

Interceptor

The processor interceptor of spring MVC is similar to the Filter in Servlet development, which is used to preprocess and post process the processor. Developers can define some interceptors to implement specific functions.

**Difference between filter and Interceptor: * * interceptor is the specific application of AOP idea.

filter

  • Part of the servlet specification that can be used by any java web project
  • After / * is configured in URL pattern, all resources to be accessed can be intercepted

Interceptor

  • The interceptor is the spring MVC framework's own. It can only be used by projects that use the spring MVC framework
  • The interceptor will only intercept the accessed controller methods. If the accessed is jsp/html/css/image/js, it will not intercept

1. Environmental construction

  • Create a new module and add web support
  • Configure web XML and spring MVC servlet xml
<?xml version="1.0" encoding="UTF-8"?>
<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>dispatcherServlet</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>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<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
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.springmvc.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven>
        <mvc:message-converters>
            <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>

</beans>
  • Create a new controller package and interceptorcontroller java
package com.springmvc.controller;

@RestController
public class InterceptorController {

    @GetMapping("/test")
    public String test() {
        System.out.println("InterceptorController==>test()Method is executed");
        return "testing environment";
    }
}
  • Add the lib package, deploy and run the environment successfully, and do not test here.

2. Implement interceptor

  • Create a new config package, myinterceptor java
package com.springmvc.config;

public class MyInterceptor implements HandlerInterceptor {
    //Execute before the method of request processing
    //If true is returned, execute the next interceptor
    //If false is returned, the next interceptor will not be executed
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=========Before method execution==========");
        return true;
    }

    //It is usually used to output interception logs
    //Executed after the request processing method is executed
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("=========After method execution==========");
    }

    //After the dispatcher servlet is processed, it is executed and cleaned up
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("=========clear==========");
    }
}
  • In spring MVC servlet Add interceptor configuration in XML
<!--Configuring Interceptors -->
<mvc:interceptors>
    <mvc:interceptor>
        <!--/** Include paths and their sub paths,For example:-->
        <!--/admin/* Intercepting is/admin/add Wait, this , /admin/add/user Will not be intercepted-->
        <!--/admin/** Intercepting is/admin/All under-->
        <mvc:mapping path="/**"/>
        <bean class="com.springmvc.config.MyInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>
  • OK, restart Tomcat and visit: http://localhost:8080/springmvc_07_interceptor/test

  • Background output:

    =========Before method execution==========
    Interceptorcontroller = = > test() method executed
    =========After method execution==========
    =========Clean up==========

3. Verify user login (access the home page only after login)

  • In index JSP provides access to the home page and login
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="${pageContext.request.contextPath}/user/home">home page</a>
    <a href="${pageContext.request.contextPath}/user/goLogin">Sign in</a>
  </body>
</html>
  • Create a new home in the WEB-INF/jsp directory JSP and login jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>home page</title>
</head>
<body>
    <h3>home page</h3>
    <p>Here are some contents of the home page...</p>
    <p>Welcome: ${username}</p>
    <a href="${pageContext.request.contextPath}/user/logout">cancellation</a>
    <a href="${pageContext.request.contextPath}/index.jsp">return index</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
    <h3>Sign in</h3>
    <form action="${pageContext.request.contextPath}/user/login" method="post">
        <label for="username">user name:</label>
        <input type="text" name="username" id="username">
        <label for="password">password:</label>
        <input type="password" name="password" id="password">
        <input type="submit" value="Sign in">
    </form>
</body>
</html>
  • In spring MVC servlet Configuring view parsing in XML
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
  • Modify interceptorcontroller Java, add request method
@Controller
@RequestMapping("/user")
public class InterceptorController {

   /* @GetMapping("/test")
    @ResponseBody
    public String test() {
        System.out.println("InterceptorController==>test()Method executed ');
        return "Test environment ";
    }
    */

    @GetMapping("/home")
    public String home(){
        return "home";  //home.jsp
    }

    @GetMapping("/goLogin")
    public String goLogin(){
        return "login";  //login.jsp
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session){
        System.out.println("username:"+username+",password:"+password);
        if ("admin".equals(username) && "123456".equals(password)) {
            session.setAttribute("username", username);
            return "redirect:/user/home";
        } else {
            return "redirect:/user/goLogin";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("username");
        return "redirect:/index.jsp";
    }
}
  • Add the interceptor logininterceptor.com under the config package java
package com.springmvc.config;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

         /*====Judge the release====*/
        // Request to log in, release
        if (request.getRequestURI().contains("goLogin")) {
            return true;
        }
        // Initiate login request and release
        if (request.getRequestURI().contains("login")) {
            return true;
        }
        //Log in successfully, enter the home page and release
        if (session.getAttribute("username")!= null) {
            return true;
        }

        //When you enter the home page for the first time, you are not satisfied with the above. Go to the login page
        request.getRequestDispatcher("/user/goLogin").forward(request, response);
        return false;
    }
}
  • In spring MVC servlet Configure another interceptor in XML
<mvc:interceptor>
    <!--intercept/user/All requests under-->
    <mvc:mapping path="/user/**"/>
    <bean class="com.springmvc.config.LoginInterceptor"/>
</mvc:interceptor>
  • Test: access: http://localhost:8080/springmvc_07_interceptor/

  • Display:

  • Click the home page link (this is the first time to click the home page). If you don't log in, you can't access it. If you are blocked, jump to the login page:

  • Enter the user name: admin, password: 123456, click the login button, login is successful, and the following is displayed:

  • Click the return index link to display:
    , and then click the home page link (here, click the home page after logging in) to access and directly jump to the home page:

  • Click the logout link to return to:
    , click the home page link (here, click the home page after logging in and logging out). If you can't access it, jump to the login page:

OK, the interception function is realized. Only when the user logs in can he access the home page!

Topics: Java Spring MVC