zoukankan      html  css  js  c++  java
  • SpringBoot中设置自定义拦截器 斧头帮

    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("/**");
    }
    
    }
  • 相关阅读:
    Json字符串转换为java对象的各种实现方法【json_lib框架、Gson、org.json】
    告别无止境的增删改查--Java代码生成器
    Java线程监听,意外退出线程后自动重启
    【技术贴】解决Program Files文件夹消失
    【技术贴】破解Myeclipse10.7
    【技术贴】解决Mysql ERROR 1045 (28000): Access denied for
    【技术贴】关闭CMD错误提示声音
    【技术贴】解决QQ空间发表文章手机不显示换行
    【技术贴】Eclipse 右键打开当前文件所在文件夹
    有趣的代码注释
  • 原文地址:https://www.cnblogs.com/guanjunhui/p/9039587.html
Copyright © 2011-2022 走看看