SpringBoot拦截器的注册

(1)、编写拦截器

 1 package cn.coreqi.config;
 2 
 3 import org.springframework.util.StringUtils;
 4 import org.springframework.web.servlet.HandlerInterceptor;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import javax.servlet.http.HttpSession;
 9 
10 public class LoginHandlerInterceptor implements HandlerInterceptor {
11 
12     //在目标方法执行之前运行此方法
13     @Override
14     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
15         HttpSession session = request.getSession();
16         String loginUser = (String) session.getAttribute("loginUser");
17         if(StringUtils.isEmpty(loginUser)){
18             //说明用户未登陆
19             request.setAttribute("msg","没有相应权限请先登陆");
20             request.getRequestDispatcher("/index.html").forward(request,response);
21             return false;
22         }
23         return true;
24     }
25 }

(2)、对拦截器进行注册

 1 package cn.coreqi.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.web.servlet.LocaleResolver;
 6 import org.springframework.web.servlet.config.annotation.*;
 7 
 8 /**
 9  * 扩展SpringMVC
10  * SpringBoot2使用的Spring5,因此将WebMvcConfigurerAdapter改为WebMvcConfigurer
11  * 使用WebMvcConfigurer扩展SpringMVC好处既保留了SpringBoot的自动配置,又能用到我们自己的配置
12  */
13 //@EnableWebMvc //如果我们需要全面接管SpringBoot中的SpringMVC配置则开启此注解,
14                 //开启后,SpringMVC的自动配置将会失效。
15 @Configuration
16 public class WebConfig implements WebMvcConfigurer {
17     @Override
18     public void addViewControllers(ViewControllerRegistry registry) {
19         //设置对“/”的请求映射到index
20         //如果没有数据返回到页面,没有必要用控制器方法对请求进行映射
21         registry.addViewController("/").setViewName("index");
22     }
23 
24     //注册拦截器
25     @Override
26     public void addInterceptors(InterceptorRegistry registry) {
27         //SpringMVC下,拦截器的注册需要排除对静态资源的拦截(*.css,*.js)
28         //SpringBoot已经做好了静态资源的映射,因此我们无需任何操作
29         registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
30                 .excludePathPatterns("/index.html","/","/user/login");
31     }
32 }
原文地址:https://www.cnblogs.com/fanqisoft/p/10324705.html