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

例子

public class AuthorityIntercept extends HandlerInterceptorAdapter {

// 放行的URL列表
private List<String> allowList = Arrays.asList("/front/**","/label/**"); private static final PathMatcher PATH_MATCHER = new AntPathMatcher(); @Value("#{configProperties['upload_path']}")
private String upload_path; private boolean isSetApplication = false; @Autowired
private RedisService redisService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
  if(!isSetApplication) {
  isSetApplication = true;
  ServletContext application = request.getSession().getServletContext();
  application.setAttribute(Constants.FILE_PATH, upload_path);
} if (!checkAllowAccess(request.getRequestURI())) {
  String token = request.getHeader("token");
  String userInfo = null;
  if(token != null){
    userInfo = this.redisService.get(token);
  }
  if (userInfo == null) {
  /*//判断是否是ajax请求
    if(isAjaxRequest(request)) {
      response.setStatus(ResultCode.USER_SESSION_INVALID.getCode());
      Result result = new Result(ResultCode.USER_SESSION_INVALID);
      result.setData(request.getContextPath() + "/front/smallLogin");
      response.getWriter().print(ResponseHelper.createResponse(result));
    } else {
      //session为空,跳到登录页
      response.sendRedirect(request.getContextPath() + "/front/login");
    }*/
  response.getWriter().write("{\"code\":4023,msg:\"please login\"}");
  return false;
  }
}
  return super.preHandle(request, response, handler);
} /**
* 检查URI是否放行
*
* @param URI
* @return 返回检查结果
*/
private boolean checkAllowAccess(String URI) {
  if (!URI.startsWith("/")) {
    URI = "/" + URI;
  }
  for (String allow : allowList) {
    if (PATH_MATCHER.match(allow, URI)) {
    return true;
  }
}
  return false;
} /**
* 判断是否是ajax请求
*
* @param request
* @return
*/
private boolean isAjaxRequest(HttpServletRequest request) {
  // 判断是否为ajax请求,默认不是
  boolean isAjaxRequest = false;
  if (StringUtils.isNotBlank(request.getHeader("x-requested-with"))
    && request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
    isAjaxRequest = true;
  }
  return isAjaxRequest;
} public List<String> getAllowList() {
  return allowList;
} public void setAllowList(List<String> allowList) {
  this.allowList = allowList;
}
}

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

/**
* 静态资源处理
* @author maming
* @date 2018年5月14日
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{ @Value("${web.upload-path}")
private String path; @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {   registry.addResourceHandler("/upload/ueditor/**").addResourceLocations("file:" + path + "ueditor/");  //虚拟路径设置
  super.addResourceHandlers(registry);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(new AuthorityIntercept()).addPathPatterns("/**");
} }

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. 对postcss以及less和sass的研究

    1.postcss PostCSS 的主要功能只有两个:第一个就是前面提到的把 CSS 解析成 JavaScript 可以操作的 抽象语法树结构(Abstract Syntax Tree,AST),第 ...

  2. 代理修饰词weak/assign/strong的区别

    基于项目报错: WebViewJavascriptBridgeBase 中定义:@property (assign) id <WebViewJavascriptBridgeBaseDelegat ...

  3. asp.net (web)选择文件夹 上传文件

    1 背景 用户本地有一份txt或者csv文件,无论是从业务数据库导出.还是其他途径获取,当需要使用蚂蚁的大数据分析工具进行数据加工.挖掘和共创应用的时候,首先要将本地文件上传至ODPS,普通的小文件通 ...

  4. CF 696 A Lorenzo Von Matterhorn(二叉树,map)

    原题链接:http://codeforces.com/contest/696/problem/A 原题描述: Lorenzo Von Matterhorn   Barney lives in NYC. ...

  5. electron原来这么简单----打包你的react、VUE桌面应用程序

    也许你不甘心只写网页,被人叫做"他会写网页",也许你有项目需求,必须写桌面应用,然而你只会前端,没关系.网上的教程很多,但是很少有能说的浅显易懂的,我尽力将electron打包应用 ...

  6. [转]Linux下防止进程使用swap及防止OOM机制导致进程被kill掉

    首先解释两个概念:swap:在linux里面,当物理内存不够用了,而又有新的程序请求分配内存,那么linux就会选择将其他程序暂时不用的数据交换到物理磁盘上(swap out),等程序要用的时候再读进 ...

  7. centOS 7 安装nginx服务

    一.安装相关依赖 yum install gcc-c++ yum install -y pcre pcre-devel yum install -y zlib zlib-devel yum insta ...

  8. 禁止、允许MySQL root用户远程访问权限

    关闭MySQL root用户远程访问权限: use mysql; update user set host = "localhost" where user = "roo ...

  9. python-网络编程urllib模块

    一.操作网络发送请求 from urllib.request import urlopen   #发送请求 from urllib.parse import urlencode   #用来把字典形式转 ...

  10. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_04 IO字节流_2_一切皆为字节

    这里的视频就是字节的形式,为了看着方便转换成了MB.一个字节就是8个二进制 包括文本,都是以字节的形式存储的