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. 【GDOI 2016 Day1】疯狂动物城

    题目 分析 注意注意:码农题一道,打之前做好心理准备. 对于操作1.2,修改或查询x到y的路径,显然树链剖分. 对于操作2,我们将x到y的路径分为x到lca(x,y)和lca(x,y)到y两部分. 对 ...

  2. shell练习--PAT题目1002:写出这个数(失败案例)

    读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字. 输入格式: 每个测试输入包含 1 个测试用例,即给出自然数 n 的值.这里保证 n 小于 1. 输出格式: 在一行内输出 n 的 ...

  3. JS&ASPDotNet_大文件上传问题

    HTML部分 <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="index.aspx. ...

  4. 【bzoj3195】【 [Jxoi2012]奇怪的道路】另类压缩的状压dp好题

    (上不了p站我要死了) 啊啊,其实想清楚了还是挺简单的. Description 小宇从历史书上了解到一个古老的文明.这个文明在各个方面高度发达,交通方面也不例外.考古学家已经知道,这个文明在全盛时期 ...

  5. centos双网卡配置

    centos双网卡问题,一个网卡配置局域网,一个网卡配置公网,如果内网访问自动走eth1,如果外网访问自动走eth2. 需要配置路由吗? 1. 首先查看机器是否是双网卡,命令如下: lspci | g ...

  6. 【洛谷P1383 高级打字机】

    题目描述 早苗入手了最新的高级打字机.最新款自然有着与以往不同的功能,那就是它具备撤销功能,厉害吧. 请为这种高级打字机设计一个程序,支持如下3种操作: 1.T x:在文章末尾打下一个小写字母x.(t ...

  7. 负载均衡环境搭建(nginx和tomcat)

    偶然看到博客上一篇负载均衡的文章,学习了一下,此处做下记录 目录 1.环境准备 2.tomcat配置 3.nginx配置 1.环境准备 第一步:java环境 第二步:nginx和pcre源码包 下载链 ...

  8. DlgResToDlgTemplate 的代码,提取EXE中的资源,然后转化成C的字符串数组

    代码来源:https://www.codeproject.com/Articles/13330/Using-Dialog-Templates-to-create-an-InputBox-in-C #i ...

  9. Fiddler代理抓取的接口的服务器返回出现"Response body is encoded. Click to decode. "

    参考与:https://blog.csdn.net/wsbl52006/article/details/53256705 解决办法: Rules > Remove All Encodings 勾 ...

  10. PL/SQL Developer 报错Dynamic Performance Tables not accessible, Automatic Statistics disabled for this session You can disable statistics in the preference menu, or obtain select priviliges on the V$ses

    可以从以下几个方面考虑: 1)单独给用户授动态性能视图的权限: SQL> grant select on V_session  to user; SQL> grant select on  ...