SpringBoot中设置自动以拦截器需要写一个类继承HandlerInterceptorAdapter并重写preHandle方法

例子

  1. public class AuthorityIntercept extends HandlerInterceptorAdapter {
  2.  
  3. // 放行的URL列表
  4. private List<String> allowList = Arrays.asList("/front/**","/label/**");
  5.  
  6. private static final PathMatcher PATH_MATCHER = new AntPathMatcher();
  7.  
  8. @Value("#{configProperties['upload_path']}")
  9. private String upload_path;
  10.  
  11. private boolean isSetApplication = false;
  12.  
  13. @Autowired
  14. private RedisService redisService;
  15. @Override
  16. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
  17. throws Exception {
  18.   if(!isSetApplication) {
  19.   isSetApplication = true;
  20.   ServletContext application = request.getSession().getServletContext();
  21.   application.setAttribute(Constants.FILE_PATH, upload_path);
  22. }
  23.  
  24. if (!checkAllowAccess(request.getRequestURI())) {
  25.   String token = request.getHeader("token");
  26.   String userInfo = null;
  27.   if(token != null){
  28.     userInfo = this.redisService.get(token);
  29.   }
  30.   if (userInfo == null) {
  31.   /*//判断是否是ajax请求
  32.     if(isAjaxRequest(request)) {
  33.       response.setStatus(ResultCode.USER_SESSION_INVALID.getCode());
  34.       Result result = new Result(ResultCode.USER_SESSION_INVALID);
  35.       result.setData(request.getContextPath() + "/front/smallLogin");
  36.       response.getWriter().print(ResponseHelper.createResponse(result));
  37.     } else {
  38.       //session为空,跳到登录页
  39.       response.sendRedirect(request.getContextPath() + "/front/login");
  40.     }*/
  41.   response.getWriter().write("{\"code\":4023,msg:\"please login\"}");
  42.   return false;
  43.   }
  44. }
  45.   return super.preHandle(request, response, handler);
  46. }
  47.  
  48. /**
  49. * 检查URI是否放行
  50. *
  51. * @param URI
  52. * @return 返回检查结果
  53. */
  54. private boolean checkAllowAccess(String URI) {
  55.   if (!URI.startsWith("/")) {
  56.     URI = "/" + URI;
  57.   }
  58.   for (String allow : allowList) {
  59.     if (PATH_MATCHER.match(allow, URI)) {
  60.     return true;
  61.   }
  62. }
  63.   return false;
  64. }
  65.  
  66. /**
  67. * 判断是否是ajax请求
  68. *
  69. * @param request
  70. * @return
  71. */
  72. private boolean isAjaxRequest(HttpServletRequest request) {
  73.   // 判断是否为ajax请求,默认不是
  74.   boolean isAjaxRequest = false;
  75.   if (StringUtils.isNotBlank(request.getHeader("x-requested-with"))
  76.     && request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
  77.     isAjaxRequest = true;
  78.   }
  79.   return isAjaxRequest;
  80. }
  81.  
  82. public List<String> getAllowList() {
  83.   return allowList;
  84. }
  85.  
  86. public void setAllowList(List<String> allowList) {
  87.   this.allowList = allowList;
  88. }
  89. }

并需要些一个类来继承WebMvcConfigurerAdapter,并重写addInterceptors方法来定义自定义的拦截器

  1. /**
  2. * 静态资源处理
  3. * @author maming
  4. * @date 2018年5月14日
  5. */
  6. @Configuration
  7. public class WebMvcConfig extends WebMvcConfigurerAdapter{
  8.  
  9. @Value("${web.upload-path}")
  10. private String path;
  11.  
  12. @Override
  13. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  14.  
  15.   registry.addResourceHandler("/upload/ueditor/**").addResourceLocations("file:" + path + "ueditor/");  //虚拟路径设置
  16.   super.addResourceHandlers(registry);
  17. }
  18. @Override
  19. public void addInterceptors(InterceptorRegistry registry) {
  20.   registry.addInterceptor(new AuthorityIntercept()).addPathPatterns("/**");
  21. }
  22.  
  23. }

SpringBoot中设置自定义拦截器的更多相关文章

  1. springboot 2.0+ 自定义拦截器

    之前项目的springboot自定义拦截器使用的是继承WebMvcConfigurerAdapter重写常用方法的方式来实现的. 以下WebMvcConfigurerAdapter 比较常用的重写接口 ...

  2. nodejs+express中设置登录拦截器

    在nodejs+express中,采用nodejs后端路由控制用户登录后,为了加强前端的安全性控制,阻止用户通过在浏览器地址栏中输入地址访问后台接口,在app.js中需要加入拦截器进行拦截: /*** ...

  3. JavaEE开发之SpringMVC中的自定义拦截器及异常处理

    上篇博客我们聊了<JavaEE开发之SpringMVC中的路由配置及参数传递详解>,本篇博客我们就聊一下自定义拦截器的实现.以及使用ModelAndView对象将Controller的值加 ...

  4. 在struts2中配置自定义拦截器放行多个方法

    源码: 自定义的拦截器类: //自定义拦截器类:LoginInterceptor ; package com.java.action.interceptor; import javax.servlet ...

  5. 关于springboot中过滤器和拦截器

    在解决跨域问题中,发现拦截器和过滤器用得不是熟练.就参考了下一下两个作者的文档.希望大家也可以汲取精华 文档1   https://blog.csdn.net/moonpure/article/det ...

  6. SpringBoot 2.x 自定义拦截器并解决静态资源访问被拦截问题

      自定义拦截器 /** * UserSecurityInterceptor * Created with IntelliJ IDEA. * Author: yangyongkang * Date: ...

  7. Struts2中一个自定义拦截器的使用

    1.自定义的拦截器的类: package it.web.interceptor; import com.opensymphony.xwork2.ActionContext; import com.op ...

  8. springboot中配置了拦截器后,拦截器无效的解决方案之一

    springboot的启动类xxxApplication不能扫描到拦截器配置类,可加上@ComponentScan(basePackages={"com.maya.common"} ...

  9. springboot中过滤器、拦截器、切片使用

    直接贴代码:采用maven工程 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project ...

随机推荐

  1. Spring IOC 实现方式

    Spring 中的 org.springframework.beans 包和 org.springframework.context 包构成了 Spring 框架 IoC 容器的基础. BeanFac ...

  2. 进阶:python3实现 插入排序

    一图胜千言,插入排序的核心逻辑如下: 将数据分成两半,前一半是已排好序的,后一半是待排序的 每次取后一半中的第一个数,在已排序的一半中,逆序依次比较,找到要插入的位置 记录插入的位置,在最后判断是否需 ...

  3. Oracle的优化

    Oracle优化:物理优化和逻辑优化.物理优化:1):Oracle的运行环境.2):合理的使用优化器.3):合理配置Oracle实例参数4):建立合适的索引(减少IO)5):将索引数据和表数据分开在不 ...

  4. Java——容器(Comparable)

    [Comparable]  

  5. 20180912-Java实例02

    Java 实例 – 删除字符串中的一个字符 以下实例中我们通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中. // Main.j ...

  6. UOJ428. 【集训队作业2018】普通的计数题

    http://uoj.ac/problem/428 题解 神仙题. 考虑最后一定是放了一个\(1\),然后把其他位置都删掉了. 再考虑到对于序列中的每个位置都对应了一次操作. 我们可以对于每个放\(1 ...

  7. SpringBoot属性配置-第三章

    1.application.yml配置#自定义参数对象book: name: A id: 1 page: 100 2.创建实体类: /** * @Auther: youqc * @Date: 2018 ...

  8. 《SQL Server 2012 T-SQL基础》读书笔记 - 1.背景

    几个缩写的全称:Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language ...

  9. (转)IDataGridViewEditingControl 接口 作用

    本文转载自:http://blog.csdn.net/zx13525079024/article/details/4814575 IDataGridViewEditingControl 接口 定义承载 ...

  10. VMware 虚拟化编程(10) — VMware 数据块修改跟踪技术 CBT

    目录 目录 前文列表 数据块修改跟踪技术 CBT 为虚拟机开启 CBT CBT 修改数据块偏移量获取函数 QueryChangedDiskAreas changeId 一个 QueryChangedD ...