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. 【leetcode】1110. Delete Nodes And Return Forest

    题目如下: Given the root of a binary tree, each node in the tree has a distinct value. After deleting al ...

  2. linux运维、架构之路-Git+Jenkins实现自动化部署

    一.Jenkins介绍          jenkins是一个用JAVA编写的开源的持续集成工具,运行在servlet容器中,支持软件配置管理(SCM)工具,可以执行基于APACHE ANT和APAC ...

  3. [JSOI2008]最大数 题解

    前言 巨佬说:要有线段树,于是蒟蒻就开始打线段树. 蒟蒻只能拿之前0分的板子题开刀了QAQ. 题解 一开始我以为插入操作不带取模,于是打了下面这个弱智玩意 下面的代码是会WA的 #include &l ...

  4. 笨办法学Python(learn python the hard way)--练习36-37

    练习37 1.Keywords(关键字) anddel fromnotwhileaselifglobal orwithassert elseifpass yield break except impo ...

  5. HTML5和CSS3兼容清单

    1.CSS3 2.CSS3选择器 3.HTML5 4.HTML5 From  

  6. CS2001 VS编译错误

    Severity Code Description Project File Line Suppression State Error CS2001 Source file 'C:\Workspace ...

  7. gsxt滑动验证码

    最后,谈谈滑动验证码. 目前,工商网站已经全面改版,全部采用了滑动验证码,上面绝大多数思路都失效了.对于滑动验证码,网上能搜到的解决方案基本都是下载图片,还原图片,算出滑动距离,然后模拟js来进行拖动 ...

  8. Android.mk【转】

    本文转载自:http://android.mk/#simple Secrets of Android.mk Introduction to Android.mk: This document desc ...

  9. 模拟赛DAY 2 T2不老梦

    [题目背景] 于万人中万幸得以相逢,刹那间澈净明通. 成为我所向披靡的勇气和惶恐,裂山海,堕苍穹. 爱若执炬迎风,炽烈而哀恸,诸般滋味皆在其中. 韶华宛转吟诵,苍凉的光荣,急景凋年深情难共. ——银临 ...

  10. linux基本目录

    / 根目录: dev : 存放抽象硬件 ib : 存放系统库文件 sbin : 存放特权级二进制文件 var : 存放经常变化的文件 home : 普通用户目录 etc : 存放配置文件目录 /etc ...