In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to use java SpringBoot interceptor". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how to use the java SpringBoot interceptor.
We are no stranger to interceptors. Interceptors are provided in both Struts 2 and Spring MVC, which can intercept requests according to URL. They are mainly used in login verification, authority verification, garbled resolution, performance monitoring and exception handling. Spring Boot also provides interceptor functionality.
In a Spring Boot project, using the interceptor feature usually requires the following three steps:
Define interceptor
Register interceptor
Specify intercept rules (if all are intercepted, static resources will also be intercepted)
Define interceptor
Defining an interceptor in Spring Boot is very simple, as long as you 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.
The return value type method declaration describes booleanpreHandle (HttpServletRequest request, HttpServletResponse response, Object handler). This method is executed before the controller processes the request method. The return value indicates whether to interrupt the subsequent operation. If true is returned, the subsequent operation will be interrupted. If false is returned, the subsequent operation will be interrupted. VoidpostHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) this method is executed after the controller processes the request method call and before parsing the view, and can be used to make further changes to the model and view in the request domain. VoidafterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) this method is executed after view rendering, and can be used to clean up resources, log information, and so on.
Example 1
Take the spring-boot-adminex project as an example, create an interceptor class called LoginInterceptor in net.biancheng.www.componet to intercept the login, 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 @ Slf4jpublic class LoginInterceptor implements HandlerInterceptor {/ * before the target method executes * * @ 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 the landing page request.setAttribute ("msg", "you do not have permission to do 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 execution {}", 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 the 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 that method to register the custom interceptor with the container.
Example 2
In the configuration class MyMvcConfig, add the following method to register the interceptor as follows.
@ Configurationpublic class MyMvcConfig implements WebMvcConfigurer {. @ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (new LoginInterceptor ());}} specify the interception rule
After registering the interceptor with the container using the registry.addInterceptor () method, we can continue to specify the interceptor's interception rules as follows.
@ Slf4j@Configurationpublic class MyConfig implements WebMvcConfigurer {. @ Override public void addInterceptors (InterceptorRegistry registry) {log.info ("register interceptor") Registry.addInterceptor (new LoginInterceptor ()) .addPathPatterns ("/ * *") / / intercepts all requests, including static resource files .diagnodePathPatterns ("/", "/ login", "/ index.html", "/ user/login", "/ css/**", "/ images/**", "/ js/**", "/ fonts/**") / / release login page, login operation, static resources}}
When the interceptor interception rule is specified, two methods are called, which are described as follows:
AddPathPatterns: this method is used to specify the interception path. For example, the intercept path is "/ * *", which means to intercept all requests, including requests for static resources.
ExcludePathPatterns: this method is used to exclude intercept paths, that is, to specify requests that do not need to be intercepted by the interceptor.
At this point, the basic function of the interceptor has been completed, and then we first implement the login function of spring-boot-adminex to prepare for the verification of landing interception.
Realize the login function
1. Move the main.html from the AdminEx template to src/main/resources/templates, as shown in the following figure.
Figure 1:main page
two。 Create a LoginController in net.bianheng.www.controller and add the method doLogin () to handle the login request. The code is as follows.
Package net.biancheng.www.controller;import lombok.extern.slf4j.Slf4j;import net.biancheng.www.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@Controllerpublic class LoginController {@ RequestMapping ("/ user/login") public String doLogin (User user, Map map, HttpSession session) {if (user! = null & & StringUtils.hasText (user.getUsername ()) & & "123456" .equals (user.getPassword () {session.setAttribute ("loginUser", user); log.info ("login successful, user name:" + user.getUsername ()) / / prevent repeated submissions using redirect return "redirect:/main.html";} else {map.put ("msg", "wrong username or password"); log.error ("login failed"); return "login" } / * @ RequestMapping ("/ main.html") public String mainPage () {return "main";} * /}
3. Add the view mapping to the configuration class MyMvcConfig, as follows.
@ Configurationpublic class MyMvcConfig implements WebMvcConfigurer {@ Override public void addViewControllers (ViewControllerRegistry registry) {/ / when visiting "/" or "/ index.html", jump directly to the landing page registry.addViewController ("/") .setViewName ("login"); registry.addViewController ("/ index.html") .setViewName ("login") / / add view mapping main.html to point to dashboard.html registry.addViewController ("/ main.html") .setViewName ("main");}.}
4. Add the following code in the appropriate place in login.html to display the error message.
Verify the function of landing and landing interception
1. Start Spring Boot and visit the home page directly through http://localhost:8080/main.html" without logging in. The result is shown in the figure below.
Figure 1: landing intercepted
two。 Enter "admin" and "admin123" in the user name and password input box on the landing page, respectively, and click the login button below. The result is shown in the figure below.
Figure 2: login failed
3. Enter "admin" and "123456" in the user name and password input box on the landing page, respectively, and click the login button below. The result is as shown below.
Figure 3: successful login
At this point, I believe you have a deeper understanding of "how to use the java SpringBoot interceptor". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.