springboot的拦截器相比springmvc 的拦截器,没有繁琐的xml配置,更为简洁。
其次需要注意下面几个方面:
1.在spring2.0之前的版本大部分都采用extends WebMvcConfigurerAdapter,把拦截器配置成一个bean,具体的方法,我不细说,网上一大堆。
2.而在spring2.0之后,这个extends WebMvcConfigurerAdapter方法就过时了,官方推荐用implements WebMvcConfigurer。其他的还和以前一样。
3.特别注意的是spring2.0之前的版本在写implements WebMvcConfigurer的时候会重写这个接口里的全部方法,这是不正常的,而在2.0之后,因为接口中默认加了default关键字,所以你可以重写里面的方法,重写几个无所谓。
建议在写拦截器的时候看看pom.xml的springboot父类版本号是多少,一定要在2.0以上,否则会只拦截请求映射,而不拦截页面。
在以上几个问题上花费了不少时间,在此特做记录,以备后用。
WebSecurityConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * autor 张喜文 * 拦截器配置 */ @Configuration public class WebSecurityConfig implements WebMvcConfigurer{ @Bean public SecurityInterceptor getSecurityInterceptor() { return new SecurityInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry){ InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); //排除配置 addInterceptor.excludePathPatterns("/index/login","/pcUser/login","/static/**");//注意需要放行静态资源,不然访问不到 //拦截配置 addInterceptor.addPathPatterns("/**"); } } |
SecurityInterceptor.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class SecurityInterceptor implements HandlerInterceptor { /** * 重写preHandle * autor 张喜文 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws IOException{ TbUser user=(TbUser)request.getSession().getAttribute("user"); String requestUrl = request.getScheme() //当前链接使用的协议 +"://" + request.getServerName()//服务器地址 + ":" + request.getServerPort();//端口号 //判断是否已有该用户登录的session if(user!=null){ return true; }else { System.out.println(requestUrl+"/index/login"); response.sendRedirect(requestUrl+"/index/login"); return false; } } } |
spring-mvc.xml
1 2 3 4 5 6 |
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/admin"/> <mvc:exclude-mapping path="/user/index"/> <bean class="com.ctgu.SecurityInterceptor"/> </mvc:interceptor> </mvc:interceptors> |