Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use interceptor in springBoot

Shulou Source: shulou.com Published: 2022-06-02 07:53:57 10月02日 Update

This article mainly explains "how springBoot uses interceptors". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it slowly to study and learn "how springBoot uses interceptors" together!

//Custom interceptor, implement HandlerInterceptor class

public class loginInterceptor implements HandlerInterceptor {

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = request.getSession().getAttribute("loginUser"); if(user==null) { request.setAttribute("error","no permission, please login"); request.getRequestDispatcher("/index.html").forward(request, response); return false; } return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}

}

//inject into container @Configuration must be written, otherwise it will not work

//WebMvcConfigurerAdapter was inherited before 1.x.x. It is not recommended to configure the configuration mode defined by yourself.

//2.x.x uses the WebMvcConfigurator class. There are many ways to configure the configuration method defined by yourself.

@Configuration

public class myConfig implements WebMvcConfigurer {

public void addInterceptors(InterceptorRegistry registry) { //Intercept all entries in the root directory, excluding/index.html / /user/login registry.addInterceptor(new loginInterceptor()).addPathPatterns("/** ") .excludePathPatterns("/index.html","/","/user/login");}

}

Thank you for reading, the above is "springBoot how to use interceptors" content, after the study of this article, I believe we have a deeper understanding of how springBoot uses interceptors, the specific use of the situation also needs to be verified. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Interceptor configuration learning content method function official container that is suggestions ideas situations articles methods more permissions root directory knowledge knowledge points articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Linux Xiaomi vpn Redmi