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 1143 最长公共子序列

    链接:https://leetcode-cn.com/problems/longest-common-subsequence 给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序 ...

  2. echart--如何将echart的配置项,放到webpack中(CHARTTEMPLATE时)

    1.假如,我们已经写好了组件,我们需要把它放入到一个环境中去 2.首先在index.html中,我们需要写一个dom结构 3.新建一个,chart.js文件(这个里面放组件的代码) 1>开始创建 ...

  3. div拖拽到iframe上方 导致 缩放和拖拽的不平滑和鼠标事件未放开 解决方法

    思路一:用在开始进行缩放(触发了resizable的start事件)为iframe添加z-index属性,将iframe放置在最下层. $("#draggable").resiza ...

  4. margin属性以及垂直外边距重叠问题

       盒子的margin属性         盒子的外边距margin 指的是当前盒子与其他盒子之间的距离,环绕在盒子周围的空白区域,属于不可见的区域,,不会影响到可见框的大小,而是会影响到盒子的位置 ...

  5. ARC模式下delloc()注意事项

    1.ARC模式下delloc()调用触发时机是对象被销毁,如self.属性=nil 2.ARC模式下delloc()里面不需要手动调用[super dealloc]; 因为系统已经自动调用,多此一举的 ...

  6. nasm不是内部或外部命令

    使用nasm编译汇编的源文件: nasm -f bin first.asm -o first.bin 报错:nasm不是内部或外部命令,这种错误一看就知道,是没有配置环境变量. 点开后,选择path, ...

  7. 可恶!学了这么久的LCA,联考的题目却是LCA+树形DP!!!可恶|!!!这几天想学学树形DP吧!先来一道入门题HDU 1520 Anniversary party

    题目描述 某大学有N个职员,编号为1~N.他们之间有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司.现在有个周年庆宴会,宴会每邀请来一个职员都会增加一定的快乐指数Ri, ...

  8. Ubuntu 16.04下使用docker部署MySQL主从复制

    (以下docker相关的命令,需要在root用户环境下或通过sudo提升权限来进行操作.) 首先更新 软件源 https://mirrors.tuna.tsinghua.edu.cn/help/ubu ...

  9. signup图片上传预览经常总结

    html <html> <head> <meta charset="utf-8" /> <meta http-equiv="X- ...

  10. jquery ajax实现文件上传

    test5.html <html> <head> <meta http-equiv="Content-Type" content="text ...