Spring boot拦截器的实现

Spring boot自带HandlerInterceptor,可通过继承它来实现拦截功能,其的功能跟过滤器类似,但是提供更精细的的控制能力。

1.注册拦截器

 @Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Bean //把我们的拦截器注入为bean
public HandlerInterceptor getMyInterceptor(){
return new Interceptor();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
// excludePathPatterns 用户排除拦截
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}

2.创建拦截器,写要过滤的请求等

 public class Interceptor implements HandlerInterceptor {

     private Logger logger = LoggerFactory.getLogger(URLInterceptor.class);

     public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
String flag = null;
flag = request.getParameter("auth");
if(StringUtils.isEmpty(flag) || !flag.equals("php")){
logger.error("error-auth:{}", flag);
return false;
} else {
logger.info("通过校验!");
return true;
}
}
}

3.取消拦截

上面是拦截所有接口,如果想某个接口取消拦截,怎么办?

新建一个类

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnAuthority { }

4.在不需要拦截的方法上面添加新增的注解,如下

@UnAuthority
@RequestMapping("/hello")
public String hello(){
return "Hello World";
}

5.修改拦截器的preHandle方法,如下

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

        // 检测请求的方法是否有UnAuthority注解,有注解不拦截,直接放行,返回true。
HandlerMethod handlerMethod = (HandlerMethod)arg2;
Method method = handlerMethod.getMethod();
UnAuthority unAuthority = method.getAnnotation(UnAuthority.class);
if(unAuthority != null ){
return true;
} String flag = null;
flag = request.getParameter("auth");
if(StringUtils.isEmpty(flag) || !flag.equals("php")){
logger.error("error-auth:{}", flag);
return false;
} else {
logger.info("通过校验!");
return true;
}
}

6.不需要auth参数访问/hello接口,成功。

新增了无需拦截的注解后,就可以根据业务需求哪些是需要拦截,哪些是不需要拦截

参考:https://blog.csdn.net/wsbgmofo/article/details/79151947

Spring boot拦截器的实现的更多相关文章

  1. 【spring boot】spring boot 拦截器

    今日份代码: 1.定义拦截器 import com.alibaba.fastjson.JSON; import org.apache.commons.collections.CollectionUti ...

  2. spring boot拦截器配置

    1.在spring boot配置文件application.properties中添加要拦截的链接 com.url.interceptor=/user/test 2.编写拦截器代码 ,创建UrlInt ...

  3. spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案(转)

    文章转自 http://blog.51cto.com/12066352/2093750 最近项目采用spring icloud,用的spring boot版本是1.5.x的,spring boot 2 ...

  4. spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案

    Springboot中静态资源和拦截器处理(踩了坑)   背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到spr ...

  5. spring boot拦截器

    实现自定义拦截器只需要3步: 1.创建我们自己的拦截器类并实现 HandlerInterceptor 接口. 2.创建一个Java类继承WebMvcConfigurerAdapter,并重写 addI ...

  6. (22)Spring Boot 拦截器HandlerInterceptor【从零开始学Spring Boot】

    上一篇对过滤器的定义做了说明,也比较简单.过滤器属于Servlet范畴的API,与Spring 没什么关系.     Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Sprin ...

  7. Spring boot 拦截器和过滤器

    1. 过滤器 Filter介绍 Filter可以认为是Servlet的一种“加强版”,是对Servlet的扩展(既可以对请求进行预处理,又可以对处理结果进行后续处理.使用Filter完整的一般流程是: ...

  8. spring boot 拦截器

    @SpringBootApplicationpublic class Application extends WebMvcConfigurerAdapter { public static void ...

  9. 九、 Spring Boot 拦截器

    过滤器属于Servlet范畴的API,与spring 没什么关系. Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截 ...

随机推荐

  1. QT状态机

    首先吐槽下网上各种博主不清不楚的讲解 特别容易让新手迷惑 总体思想是这样的:首先要有一个状态机对象, 顾名思义,这玩意就是用来容纳状态的.然后调用状态机的start()函数它就会更具你的逻辑去执行相关 ...

  2. Java Web基础面试题整理

    Tomcat的缺省端口是多少,怎么修改 tomcat默认缺省端口是8080 修改方法: 找到Tomcat目录下的conf文件夹 进入conf文件夹里面找到server.xml文件 打开server.x ...

  3. Romantic HDU - 2669(扩欧)

    #include<bits/stdc++.h> using namespace std; typedef long long LL; void gcd(LL a, LL b, LL &am ...

  4. Python3 反射

    反射 python面向对象中的反射:通过字符串的形式操作对象相关的属性 hasattr(obj,name) # hasattr(obj, name) # 判断一个对象是否有指定的属性name,返回Tr ...

  5. Windows Server 2008创建域环境

    介绍一下域环境搭建,域主要用于中大型企业,小型企业计算机数量不多,而中大型企业计算机比较多,使用域可以方便管理,安全性也比在工作组中安全 1.安装完操作系统默认都属于WORKGROUP工作组. 2.安 ...

  6. Winform 自定义文本框

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  7. (三十九)c#Winform自定义控件-面包屑导航

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...

  8. 剑指Offer(十八):二叉树的镜像

    剑指Offer(十八):二叉树的镜像 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/baidu ...

  9. bootstrap-datetimepicker时间插件使用

    html头部引入相关的js和css <link rel="stylesheet" type="text/css" href="css/boots ...

  10. Java中时间格式处理,指定N天/小时等之后的时间

    1)根据当前时间,获取具体的时刻的时间 N天前 M小时之前 可用 new Date().getTime() - 24 * 60 * 60 * 1000*N[N天之前]的方法来获取处理时间之后的具体的值 ...