springboot设置过滤器、监听器、拦截器
其实这篇文章算不上是springboot的东西,我们在spring普通项目中也是可以直接使用的
设置过滤器:
以前在普通项目中我们要在web.xml中进行filter的配置,但是只从servlet 3.0后,我们就可以在直接在项目中进行filter的设置,因为她提供了一个注解@WebFilter(在javax.servlet.annotation包下),使用这个注解我们就可以进行filter的设置了,同时也解决了我们使用springboot项目没有web.xml的尴尬,使用方法如下所示
@WebFilter(urlPatterns="/*",filterName="corsFilter", asyncSupported = true)
public class CorsFilter implements Filter{ @Override
public void init(FilterConfig filterConfig) throws ServletException { } @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;
chain.doFilter(servletRequest, servletResponse);
} @Override
public void destroy() { } }
其实在WebFilter注解中有一些属性我们需要进行设置, 比如value、urlPatterns,这两个属性其实都是一样的作用,都是为了设置拦截路径,asyncSupported这个属性是设置配置的filter是否支持异步响应,默认是不支持的,如果我们的项目需要进行请求的异步响应,请求经过了filter,那么这个filter的asyncSupported属性必须设置为true不然请求的时候会报异常。
设置拦截器:
编写一个配置类,继承org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter或者org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport并重写addInterceptors(InterceptorRegistry registry)方法,其实父类的addInterceptors(InterceptorRegistry registry)方法就是个空方法。使用方法如下:
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport { @Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration registration = registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
});
// 配置拦截路径
registration.addPathPatterns("/**");
// 配置不进行拦截的路径
registration.excludePathPatterns("/static/**");
}
}
配置监听器:
一般我们常用的就是request级别的javax.servlet.ServletRequestListener和session级别的javax.servlet.http.HttpSessionListener,下面以ServletRequestListener为例,编写一个类实现ServletRequestListener接口并实现requestInitialized(ServletRequestEvent event)方法和requestDestroyed(ServletRequestEvent event)方法,在实现类上加上@WebListener(javax.servlet.annotation包下),如下所示
@WebListener
public class RequestListener implements ServletRequestListener { @Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("请求结束");
} @Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("请求开始");
}
}
这样每一个请求都会被监听到,在请求处理前equestInitialized(ServletRequestEvent event)方法,在请求结束后调用requestDestroyed(ServletRequestEvent event)方法,其实在spring中有一个非常好的例子,就是org.springframework.web.context.request.RequestContextListener类
public class RequestContextListener implements ServletRequestListener { private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =
RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES"; @Override
public void requestInitialized(ServletRequestEvent requestEvent) {
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
throw new IllegalArgumentException(
"Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
}
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(attributes);
} @Override
public void requestDestroyed(ServletRequestEvent requestEvent) {
ServletRequestAttributes attributes = null;
Object reqAttr = requestEvent.getServletRequest().getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);
if (reqAttr instanceof ServletRequestAttributes) {
attributes = (ServletRequestAttributes) reqAttr;
}
RequestAttributes threadAttributes = RequestContextHolder.getRequestAttributes();
if (threadAttributes != null) {
// We're assumably within the original request thread...
LocaleContextHolder.resetLocaleContext();
RequestContextHolder.resetRequestAttributes();
if (attributes == null && threadAttributes instanceof ServletRequestAttributes) {
attributes = (ServletRequestAttributes) threadAttributes;
}
}
if (attributes != null) {
attributes.requestCompleted();
}
} }
在这个类中,spring将每一个请求开始前都将请求进行了一次封装并设置了一个threadLocal,这样我们在请求处理的任何地方都可以通过这个threadLocal获取到请求对象,好处当然是有的啦,比如我们在service层需要用到request的时候,可以不需要调用者传request对象给我们,我们可以通过一个工具类就可以获取,岂不美哉。
扩充:在springboot的启动类中我们可以添加一些ApplicationListener监听器,例如:
@SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication application = new SpringApplication(DemoApplication.class);
application.addListeners(new ApplicationListener<ApplicationEvent>() {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.err.println(event.toString());
}
});
application.run(args);
}
}
ApplicationEvent是一个抽象类,她的子类有很多比如ServletRequestHandledEvent(发生请求事件的时候触发)、ApplicationStartedEvent(应用开始前触发,做一些启动准备工作)、ContextRefreshedEvent(容器初始化结束后触发),其他还有很多,这里不再多说,但是这些ApplicationListener只能在springboot项目以main方法启动的时候才会生效,也就是说项目要打jar包时才适用,如果打war包,放在Tomcat等web容器中是没有效果的。
springboot设置过滤器、监听器、拦截器的更多相关文章
- JavaWeb过滤器.监听器.拦截器-原理&区别-个人总结
对比项 拦截器 过滤器 机制 反射机制 函数回调 是否依赖servlet容器 是 否 请求处理 只能对action请求起作用 几乎所有的请求起作用 对action处理 可以访问action上下文.值栈 ...
- springboot(五)过滤器和拦截器
前言 过滤器和拦截器二者都是AOP编程思想的提现,都能实现诸如权限检查.日志记录等.二者有一定的相似之处,不同的地方在于: Filter是servlet规范,只能用在Web程序中,而拦截器是Sprin ...
- JavaWeb过滤器.监听器.拦截器-原理&区别(转)
1.拦截器是基于java的反射机制的,而过滤器是基于函数回调 2.过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 3.拦截器只能对action请求起作用,而过滤器则可以对几乎所有的 ...
- AOP,过滤器,监听器,拦截器【转载】
面向切面编程(AOP是Aspect Oriented Program的首字母缩写) ,我们知道,面向对象的特点是继承.多态和封装.而封装就要求将功能分散到不同的对象中去,这在软件设计中往往称为职责分配 ...
- JavaWeb过滤器.监听器.拦截器-?原理&区别
过滤器可以简单理解为“取你所想取”,忽视掉那些你不想要的东西:拦截器可以简单理解为“拒你所想拒”,关心你想要拒绝掉哪些东西,比如一个BBS论坛上拦截掉敏感词汇. 1.拦截器是基于java的反射机制,过 ...
- SpringBoot(十一)过滤器和拦截器
v博客前言 在做web开发的时候,过滤器(Filter)和拦截器(Interceptor)很常见,通俗的讲,过滤器可以简单理解为“取你所想取”,忽视掉那些你不想要的东西:拦截器可以简单理解为“拒你所想 ...
- springboot使用过滤器和拦截器
1.Filter过滤器 @Componentpublic class AuthFilter implements Filter { private static final Log log = Log ...
- 过滤器 & 监听器 & 拦截器
过滤器: https://blog.csdn.net/MissEel/article/details/79351231 https://blog.csdn.net/qq_32363305/articl ...
- springboot配置过滤器和拦截器
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Http ...
- 关于springboot中过滤器和拦截器
在解决跨域问题中,发现拦截器和过滤器用得不是熟练.就参考了下一下两个作者的文档.希望大家也可以汲取精华 文档1 https://blog.csdn.net/moonpure/article/det ...
随机推荐
- 数据结构和算法(Golang实现)(18)排序算法-前言
排序算法 人类的发展中,我们学会了计数,比如知道小明今天打猎的兔子的数量是多少.另外一方面,我们也需要判断,今天哪个人打猎打得多,我们需要比较. 所以,排序这个很自然的需求就出来了.比如小明打了5只兔 ...
- Julia基础语法复数和分数
1.复数 2.分数
- 数据结构与算法--树(tree)结构
树 二叉树 遍历原则:前序遍历是根左右, 中序遍历是左根右,后序遍历是左右根. 二叉搜索树 特点:对于树中的每个节点X,它的左子树中所有节点的值都小于X,右子树中所有节点的值都大于X. 遍历:采取二叉 ...
- mysql 创建表 索引 主键 引擎 自增 注释 编码等
CREATE TABLE text(id INT(20) COMMENT '主键',NAME VARCHAR(20) COMMENT '姓名',PASSWORD VARCHAR(20) COMMENT ...
- SQL Server 之T-SQL基本语句 (2)
接下来继续用上述例子来总结知识点. 用通配符进行过滤 LIKE操作符 //用来选择与条件一样或部分相似的数据 select name from person where name like 'chen ...
- python慎用os.getcwd() ,除非你知道【文件路径与当前工作路径的区别】
当你搜索 "获取当前文件路径" 时,有的文章会提到用os.getcwd(),但是这玩意要慎用! 废话不多说,直接上例子: E:\program_software\Pycharm\y ...
- MySQL数据库缓存操作
安装: 启动的话: -d:以后台的方式进行: -l:选择监听指定的ip服务地址:-m:给他分配多大的内存:-p:端口号默认的端口为11211的服务端口: 另一个: 安装:telnet 这个可以用来测试 ...
- Windows API 中 OVERLAPPED 结构体 初始化
出处:https://github.com/microsoft/Windows-classic-samples/blob/1d363ff4bd17d8e20415b92e2ee989d615cc0d9 ...
- 讲讲python中函数的参数
python中函数的参数 形参:定义函数时代表函数的形式参数 实参:调用函数时传入的实际参数 列如: def f(x,y): # x,y形参 print(x, y) f(1, 2) # 1, 2 实参 ...
- 【ubuntu】windows+ubuntu 设置windows为第一启动项
进入ubuntu系统 sudo su vim /etc/default/grub 更改GRUB_DEFAULT=后的值默认是0,如果你的windows启动项在第5个就改成4.改完之后退出保存输入 up ...