Spring Boot interceptor essence

We are no stranger to interceptors. Both Struts 2 and Spring MVC provide interceptor functions, which can intercept requests based on URLs, and are mainly used in login verification, authority verification, garbled code resolution, performance monitoring and exception handling And other functions. Spring Boot also provides interceptor functionality.

In a Spring Boot project, using the interceptor function usually requires the following three steps:
define the interceptor;
register the interceptor;
specify the interception rules (if all are intercepted, static resources will also be intercepted).
Defining interceptors
Defining interceptors in Spring Boot is very simple, just create an interceptor class and implement the HandlerInterceptor interface.

The following three methods are defined in the HandlerInterceptor interface, as shown in the following table.
insert image description here
Example 1
Take the spring-boot-adminex project as an example. Create an interceptor class named LoginInterceptor in net.biancheng.www.componet to intercept login. The code is as follows.
package net.biancheng.www.componet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor { /** * Before the target method is executed * * @param request * @param response * @param handler * @return * @throws Exception /









@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object loginUser = request.getSession().getAttribute(“loginUser”); if (loginUser == null) { //not logged in, return to login page request.setAttribute("msg", "You do not have permission to perform this operation, please log in first!"); request.getRequestDispatcher("/index.html").forward(request, response); return false; } else { // Release return true; } } /











*
* After the target method is executed
*
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("postHandle execute {}", modelAndView); } /


*
* After the page is rendered
*
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("afterCompletion execution exception {}", ex); } } register interceptor




Create a configuration class that implements the WebMvcConfigurer interface (a class annotated with @Configuration), override the addInterceptors() method, and call the registry.addInterceptor() method in this method to register the custom interceptor in the container.
Example 2
In the configuration class MyMvcConfig, add the following method to register the interceptor, the code is as follows.
@Configuration
public class MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()); } } Specify the interception rules Modify the code of the addInterceptors() method in the MyMvcConfig configuration class and continue to specify the interceptor The interception rules, the code is as follows. @Slf4j @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) {














log.info("Registration Interceptor");
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/ ") //Intercept all requests, including static resource files.excludePathPatterns
("/", "/login", " /index.html", "/user/login", "/css/
", "/images/ ", "/js/ ", "/fonts/**"); //Release login page, login operation, static resource
}
}

When specifying interceptor interception rules, two methods are called. The description of these two methods is as follows:
addPathPatterns: This method is used to specify the interception path. For example, the interception path is "/**", which means to intercept all requests, including static resource request.
excludePathPatterns: This method is used to exclude interception paths, that is, specify requests that do not need to be intercepted by the interceptor.

So far, the basic functions of the interceptor have been completed. Next, we first implement the login function of spring-boot-adminex to prepare for the verification login interception.

Realize the login function

  1. Rename index.html in the AdminEx template to main.html, and move it to src/main/resources/templates, as shown in the figure below.

insert image description here

Figure 1: main page

  1. Create a LoginController in tangyu9880.controller, and add the method doLogin() to process the login request, the code is as follows.
    package tangyu9880.controller;
    import lombok.extern.slf4j.Slf4j;
    import tangyu9880.bean.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.StringUtils;
    import org.springframework.web.bind.annotation. GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import javax.servlet.http.HttpSession;
    import java.util.Map;
    @Slf4j
    @Controller
    public class LoginController { @RequestMapping("/user/login")

    public String doLogin(User user, Map<String, Object> map, HttpSession session) { if (user != null && StringUtils.hasText(user.getUsername()) && “123456”.equals(user.getPassword())) { session.setAttribute("loginUser", user); log.info("Successful login, username:" + user.getUsername()); //Prevent repeated submissions using redirection return "redirect:/main.html"; } else { map.put("msg", "Incorrect username or password"); log.error("Login failed"); return "login"; } } /* @RequestMapping("/main.html") public String mainPage(){ return "main"; }*/ }
















  2. Add view mapping in the configuration class MyMvcConfig, the code is as follows.
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { //When visiting "/" or "/index.html", jump directly to the login page registry.addViewController("/"). setViewName("login"); registry.addViewController("/index.html").setViewName("login"); //Add view mapping main.html pointing to dashboard.html registry.addViewController(“/main.html”). setViewName("main"); } ... }









  3. Add the following code in the appropriate place of login.html to display the error message.

Verify login and login interception function 1. Start Spring Boot, and directly access the homepage through "http://localhost:8080/main.html" without logging in, the result is as shown in the figure below. ![Insert picture description here](https://img-blog.csdnimg.cn/676e3a413b6b485faf2439d79e5fcac3.png)

Login interception
Figure 1: Login is intercepted

  1. Enter "admin" and "admin123" respectively in the user name and password input boxes on the login page, and click the login button below, the result is as shown in the figure below.
    insert image description here

Login failed
Figure 2: Login failed

  1. Enter "admin" and "123456" respectively in the user name and password input boxes on the login page, and click the login button below, the result is as shown in the figure below.
    insert image description here

Landed successfully

Guess you like

Origin blog.csdn.net/weixin_64842782/article/details/125106848