啦~嘿~呦~又是美好的一天呀~九月份第6篇还行吧(九月还差3篇啦~那就水够啦)
拦截器在我们项目中经常会用到哒~
那我先讲如何用吧(也是怕自己忘记)
用一个简单的登录拦截例子步骤吧:
1.创建我们自己的拦截器类并实现 HandlerInterceptor 接口
2.实现WebMvcConfigurer接口中的addInterceptors方法把自定义的拦截器类添加进来即可
ps:Spring boot 1.x是继承WebMvcConfigurerAdapter,等下会说到,但下面会是以spring boot 2.x为例子。
自定义拦截器代码:
package com.glj.componemt; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created with IntelliJ IDEA. * User: GuoLiangJun * Date: 2019/9/8 * Time: 23:21 */ public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = request.getSession().getAttribute("loginUser"); if(user == null){ //未登陆,返回登陆页面 request.setAttribute("msg","没有权限请先登陆"); request.getRequestDispatcher("/index.html").forward(request,response); return false; }else{ //已登陆,放行请求 return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
上面的代码就是判定session是否存在,存在则放行(辣鸡例子而已)
实现WebMvcConfigurer接口中的addInterceptors方法把自定义的拦截器类添加进来代码:
package com.glj.config; import com.glj.componemt.LoginHandlerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.*; /** * Created with IntelliJ IDEA. * User: GuoLiangJun * Date: 2019/09/04 * Time: 16:51 */ @Configuration public class MyWebMvcConfig implements WebMvcConfigurer { /** * 添加拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration interceptorRegistration = registry.addInterceptor(new LoginHandlerInterceptor()); interceptorRegistration.excludePathPatterns("/asserts/**","/error/**","/index.html","/","/user/login"); interceptorRegistration.addPathPatterns("/**"); } }
其中addPathPatterns("/**")对所有请求都拦截,但是(excludePathPatterns)排除了一些连接请求的拦截。
spring 1.x之前的话,添加拦截器是不需要考虑静态资源目录,因为拦截器是不会拦截的。
而spring 2.x后呢,你会发现静态资源访问不到的。所以需要在excludePathPatterns上排除uri连接。
如果是大本科,英语厉害去spring看文档,我垃圾大专狗只能谷歌翻译+doc了~
也可参考:https://my.oschina.net/dengfuwei/blog/1795346
好了以上写的都是扯淡的别信,88~