How to use interceptor in springBoot
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!