SpringBoot如何添加拦截器
来源:互联网 发布:网络大电影编剧收费 编辑:程序博客网 时间:2024/06/05 20:59
在web开发的过程中,为了实现登录权限验证,我们往往需要添加一个拦截器在用户的的请求到达controller层的时候实现登录验证,那么SpringBoot如何添加拦截器呢?
步骤如下:
1.继承WebMvcConfigureAdapter类,覆盖其addInterceptors接口,注册我们自定义的拦截器:
/** * * 注册拦截器 * Created by SYSTEM on 2017/8/16. */ public class WebAppConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { //注册自定义拦截器,添加拦截路径和排除拦截路径 registry.addInterceptor(new InterceptorConfig()).addPathPatterns("api/path/**").excludePathPatterns("api/path/login"); } }2.实现HandlerInterceptor接口,重写接口中的三个方法:
public class InterceptorConfig implements HandlerInterceptor{ private static final Logger log = LoggerFactory.getLogger(InterceptorConfig.class); /** * 进入controller层之前拦截请求 * @param httpServletRequest * @param httpServletResponse * @param o * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { log.info("---------------------开始进入请求地址拦截----------------------------"); HttpSession session = httpServletRequest.getSession(); if(!StringUtils.isEmpty(session.getAttribute("userName"))){ return true; } else{ PrintWriter printWriter = httpServletResponse.getWriter(); printWriter.write("{code:0,message:\"session is invalid,please login again!\"}"); return false; } } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { log.info("--------------处理请求完成后视图渲染之前的处理操作---------------"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { log.info("---------------视图渲染之后的操作-------------------------0"); } }
这样我们就可以在用户请求到达controller层实现登录拦截了,所有用户请求都会被拦截,在prehandle方法进行登录判断,返回true则验证通过,否则失败
阅读全文
0 0
- SpringBoot如何添加拦截器
- SpringBoot如何添加拦截器
- springboot添加拦截器
- springboot添加拦截器
- springboot 拦截器配置
- SpringBoot--实现拦截器
- springboot使用拦截器
- SpringBoot拦截器
- SpringBoot 自定义拦截器
- SpringBoot-拦截器
- SpringBoot之拦截器
- SpringBoot 实现拦截器
- springBoot 使用继承WebMvcConfigurerAdapter 添加多个拦截器和继承HandlerInterceptorAdapter创建拦截器
- SpringBoot拦截器的使用
- SpringBoot之Interceptor拦截器
- SpringBoot AOP 拦截器 Aspect
- SpringBoot拦截器的使用
- springboot--页面访问拦截器
- 成为Java GC专家(3)—如何优化Java垃圾回收机制
- 第十一周 项目5
- Redis学习--JedisCluster源码解读
- Andrew Ng's deeplearning Course3Week1 ML Strategy(结构化机器学习)
- MyBatis
- SpringBoot如何添加拦截器
- 关于递推算法的研究
- a newbie in Porto Seguro’s Safe Driver Prediction(solo参赛 TOP 5%)
- c++之数组与字符串
- react-native总结之项目开发环境创建
- 利用 js-xlsx 实现 Excel 文件导入并解析Excel数据成json格式的数据并且获取其中某列数据
- Ambari启用认证,发送restful请求报错[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)
- linux14.04 +webdriver+selenium+pycharm
- Python中的类,模块,函数