The spring MVC interceptor of kit's learning process

Keywords: JSP Spring Java IntelliJ IDEA

Day 14 of Kite's learning framework

1. Spring MVC interceptor

Introduction: Spring MVC's processor interceptor is similar to the Filter in Servlet development, which is used for preprocessing and postprocessing the processor. Users can define some interceptors to implement specific functions. When it comes to interceptors, I also want to give you a word - Interceptor Chain. Interceptor Chain is to link interceptors into a chain in a certain order. When an intercepted method or field is accessed, the interceptors in the Interceptor Chain are called in the order they were previously defined.

Filters in domain servlet s for comparison
Filters are part of the servlet specification and can be used by any java web project.
The interceptor is the spring MVC framework's own. Only projects that use the spring MVC framework can use it.
After the filter is configured with / * in URL pattern, it can intercept all resources to be accessed.
Interceptor is a controller method that can only intercept the access. If the access is jsp, html,css,image or js, it will not be intercepted.
It is also the application of AOP.
To customize interceptors, we need to implement the HandlerInterceptor interface.

1.1 custom interceptor steps

1.1.1 create a controller class

package cn.kitey.controller;


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

/**
 * Intercepted controller method
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/testInterceptor")
    public String testException()  {
        System.out.println("testInterceptor Executed!");


        return  "success";
    }


}

1.1.2 create a index.jsp Page, used to enter the controller, a success.jsp The page is used to jump to the success page, a error.jsp Page, used for page Jump in interceptor

index.jsp page

<%--
  Created by IntelliJ IDEA.
  User: Small kite
  Date: 2020/6/19
  Time: 22:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>SpringMVC Interceptor</title>

    <h3>SpringMVC Interceptor</h3>
    <a href="user/testInterceptor">exception handling</a>
</head>
<body>

</body>
</html>


Note that under the pages package, the view parser we set is the. jsp file under this path
success.jsp page

<%--
  Created by IntelliJ IDEA.
  User: Little kite
  Date: 2020/6/19
  Time: 22:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
    //Forwarding succeeded!

    <% System.out.println("success.jsp Page executed"); %>
</body>
</html>

error.jsp page

<%--
  Created by IntelliJ IDEA.
  User: Small kite
  Date: 2020/6/20
  Time: 10:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error</title>
</head>
<body>

<h3>ERROR page</h3>
</body>
</html>


1.1.3 create an interceptor package in which MyInterceptor class is created to implement the interface HandlerInterceptor

The overridden methods are:
public boolean preHandle(): the preprocessing method, which is executed before the controller is executed, contains the return value. If the return value is false, it means no release. However, it can be executed in this method, request forwarding, and jump to the error page request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
public void postHandle(): a post-processing method. After executing the controller, the success.jsp Prior to execution. There is no return value. You can execute the request forwarding method, but it will execute success.jsp page
public void afterCompletion(): the final processing method, in the success.jsp After the page is executed, the method is executed, and the request forwarding method cannot be performed.

package cn.kitey.interceptor;

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

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


/**
 * Custom interceptor class
 */
public class MyInterceptor implements HandlerInterceptor {

    /**
     * Preprocessing, before the controller method is executed
     * return true :Release, execute next interceptor, execute method in controller
     * return false No release
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor The interceptor executed..... Pretreatment!");

        //request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);

        //No release or release is set here
        return true;

    }

    /**
     * After processing method, when returning after controller, the executed method success.jsp Pre method execution
     * @param request
     * @param response
     * @param handler
     * @param
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor The interceptor executed..... After treatment!");
        //You can also jump to the page by request forwarding (but later success.jsp Page will also execute)
        //request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);

    }

    /**
     * Final treatment, at success.jsp After execution, execute the method
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor The interceptor executed..... Final treatment!");
        //This method can not forward the page request!!
    }
}


1.1.4 create an interceptor to intercept

package cn.kitey.interceptor;

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

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


/**
 * Custom interceptor class
 */
public class MyInterceptor1 implements HandlerInterceptor {

    /**
     * Preprocessing, before the controller method is executed
     * return true :Release, execute next interceptor, execute method in controller
     * return false No release
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor The interceptor executed..... Pretreatment 111!");

        //request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);

        //No release or release is set here
        return true;

    }

    /**
     * After processing method, when it returns after controller, the executed method success.jsp Pre method execution
     * @param request
     * @param response
     * @param handler
     * @param
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor The interceptor executed..... Aftertreatment 111!");
        //You can also jump to the page by request forwarding (but later success.jsp Page will also execute)
        //request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);

    }

    /**
     * Final treatment, at success.jsp After execution, execute the method
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor The interceptor executed..... Final treatment 111!");
        //This method can not forward the page request!!
    }
}


1.1.5 configuring interceptors in spring MVC

Configure label as interceptors
Where we configure two custom interceptors
MyInterceptor: interception path is / uesr/
. MyInterceptor1: intercept path:/**

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:nvc="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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--Turn on scan of package path-->
    <context:component-scan base-package="cn.kitey"></context:component-scan>

    <!--Turn on view parser -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--The path where the injection file is located-->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!--Configure the file suffix for scanning-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--Configuring Interceptors -->
    <nvc:interceptors>
        <mvc:interceptor>
            <!--Configure the path to intercept-->
            <mvc:mapping path="/user/*"/>
            <bean class="cn.kitey.interceptor.MyInterceptor"></bean>
        </mvc:interceptor>
        
        <!--Add interceptor path-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="cn.kitey.interceptor.MyInterceptor1"></bean>
        </mvc:interceptor>
        
    </nvc:interceptors>



    <!--open SpringMVC Framework annotation support-->
    <mvc:annotation-driven ></mvc:annotation-driven>



</beans>

Operation result chart
index.jsp page

Console display

Jump page

If it is set not to release, it will not be striped to the page, and it will jump to error.jsp page

Posted by Tilemachos on Fri, 19 Jun 2020 20:50:36 -0700