springboot_4 spring boot 使用servlet,filter,listener和interceptor
上一篇我们学习了 spring boot 利用Controller响应数据与响应页面。 一般的Web开发使用 Controller 基本上可以完成大部分需求,但是有的时候我们还是会用到 Servlet、Filter、Listener 等等。
在spring boot中添加自己的Servlet、Filter、Listener有两种方法
- 代码注册: 通过ServletRegistrationBean、 FilterRegistrationBean 和ServletListenerRegistrationBean 获得控制。
- 注解注册: 在SpringBootApplication 上使用@ServletComponentScan注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
spring boot 中注册servlet
代码注册
- 创建Servlet类:AaServlet.java。
public class AaServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost()");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h1>AaServlet</h1>");
}
}
- 通过ServletRegistrationBean注册。
//Project2Application.java
@Bean
public ServletRegistrationBean AaServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new AaServlet());
registration.addUrlMappings("/a");
return registration;
}
- 运行测试。

注解注册
- 创建Servlet类:BbServlet.java。
@WebServlet(urlPatterns = "/b")
public class BbServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost()");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h1>BbServlet</h1>");
}
}
- 添加注解@ServletComponentScan。
@ServletComponentScan
@SpringBootApplication
public class Project2Application {
public static void main(String[] args) {
SpringApplication.run(Project2Application.class, args);
}
@Bean
public ServletRegistrationBean AaServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new AaServlet());
registration.addUrlMappings("/a");
return registration;
}
}
- 运行测试。

filter 和 listener的注册和servlet一样。这里就不多说了。
接下来说一下拦截器。
自定义拦截器
Spring提供了HandlerInterceptor(拦截器)。它的功能跟过滤器类似,但是提供更精细的的控制能力:在request被响应之前、request被响应之后、视图渲染之前以及request全部结束之后。我们不能通过拦截器修改request内容,但是可以通过抛出异常(或者返回false)来暂停request的执行。
spring boot提供了一些拦截器,我们可以直接拿来使用,比如:
- ConversionServiceExposingInterceptor
- CorsInterceptor
- LocaleChangeInterceptor
- PathExposingHandlerInterceptor
- ResourceUrlProviderExposingInterceptor
- ThemeChangeInterceptor
- UriTemplateVariablesHandlerInterceptor
- UserRoleAuthorizationInterceptor
我们也可以自己定义拦截器,定义拦截器的步骤大致分为:
1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。
2、创建一个Java类继承WebMvcConfigurerAdapter,并重写addInterceptors 方法。
3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。
我们来亲自试一下:
- 创建我们自己的拦截器
//MyInterceptor2
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("MyInterceptor1==========>在请求处理之前进行调用(Controller方法调用之前)");
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor1==========>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("MyInterceptor1==========>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
}
}
//MyInterceptor2
public class MyInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("MyInterceptor2==========>在请求处理之前进行调用(Controller方法调用之前)");
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor2==========>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("MyInterceptor2==========>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
}
}
创建一个Java类继承WebMvcConfigurerAdapter,并重写addInterceptors 方法,添加拦截器。
//MyWebAppConfigurer
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
测试:运行项目,随便访问一个路径,比如http://localhost:8080/test
浏览器会报错,不用管,看控制台。

拦截器已经起作用了。
值得注意的是:只有经过DispatcherServlet 的请求,才会走拦截器链,我们自定义的Servlet 请求是不会被拦截的,比如我们自定义的Servlet地址是不会被拦截器拦截的。
但是过滤器不同。不管是属于哪个Servlet 只要复合过滤器的过滤规则,过滤器都会拦截。
本篇文章就先介绍到这里,如果哪里讲的不明白,请及时与我联系。
参考文章:Spring Boot 拦截器
作者:cleverfan
链接:https://www.jianshu.com/p/fba5c0fd09bb
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
springboot_4 spring boot 使用servlet,filter,listener和interceptor的更多相关文章
- Spring Boot整合Servlet,Filter,Listener,访问静态资源
目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...
- spring boot:多个filter/多个interceptor/多个aop时设置调用的先后顺序(spring boot 2.3.1)
一,filter/interceptor/aop生效的先后顺序? 1,filter即过滤器,基于servlet容器,处于最外层, 所以它会最先起作用,最后才停止 说明:filter对所有访问到serv ...
- spring boot整合servlet、filter、Listener等组件方式
创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...
- Spring Boot 注册 Servlet 的三种方法,真是太有用了!
本文栈长教你如何在 Spring Boot 注册 Servlet.Filter.Listener. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spr ...
- spring boot配置Servlet容器
Spring boot 默认使用Tomcat作为嵌入式Servlet容器,只需要引入spring-boot-start-web依赖,默认采用的Tomcat作为容器 01 定制和修改Servlet容器 ...
- ServletContextInitializer添加 servlet filter listener
ServletContextInitializer添加 servlet filter listener https://www.cnblogs.com/pomer-huang/p/9639322.ht ...
- [转] Spring Boot实战之Filter实现使用JWT进行接口认证
[From] http://blog.csdn.net/sun_t89/article/details/51923017 Spring Boot实战之Filter实现使用JWT进行接口认证 jwt(j ...
- SpringBoot学习笔记(6)----SpringBoot中使用Servlet,Filter,Listener的三种方式
在一般的运用开发中Controller已经大部分都能够实现了,但是也不排除需要自己实现Servlet,Filter,Listener的方式,SpringBoot提供了三种实现方式. 1. 使用Bean ...
- SpringBoot---注册Servlet,Filter,Listener
1.概述 1.1.当使用 内嵌的Servlet容器(Tomcat.Jetty等)时,将Servlet,Filter,Listener 注册到Servlet容器的方法: 1.1.1.直接注册Bean ...
随机推荐
- shell编程系列19--文本处理三剑客之awk中的字符串函数
shell编程系列19--文本处理三剑客之awk中的字符串函数 字符串函数对照表(上) 函数名 解释 函数返回值 length(str) 计算字符串长度 整数长度值 index(str1,str2) ...
- Sword zlog日志库使用
配置文件*.conf 配置文件具体内容如下: [global] #改变量可以不写,默认是true,如果使用设置为true时,Zlog就会严格检查所用格式和规则,否则,忽略所用格式和规则. strict ...
- ifc osg施工现场模拟
基于ifc数据模型的施工现场模拟
- 【Linux】反向代理
Nginx server { root /data/wwwroot/; server_name www.test.com; location / { proxy_http_version 1.1; p ...
- 果卿居士-《四种清净明诲》之不淫欲 -------------------------------------------------------------------------------- (转自学佛网:http://www.xuefo.net/nr/article19/186541.html)
“如不断淫”, “阿难,如不断淫,修禅定者,如蒸砂石.欲其成饭.经百千劫.只名热砂.何以故.此非饭本.砂石成故.” 阿难啊,如果这个修行的人,最后不能断除淫欲,包括夫妻之间的淫欲,如果你不能断除这个欲 ...
- PAT 甲级 1064 Complete Binary Search Tree (30 分)(不会做,重点复习,模拟中序遍历)
1064 Complete Binary Search Tree (30 分) A Binary Search Tree (BST) is recursively defined as a bin ...
- js Date.parse()时区问题
比较两个时间,parse() 方法可解析一个日期时间字符串,并返回 1970/1/1 午夜距离该日期时间的毫秒数.Date.parse时间多了8小时. 正确的方法: var nowDate = Dat ...
- 改进初学者的PID-微分冲击
最近看到了Brett Beauregard发表的有关PID的系列文章,感觉对于理解PID算法很有帮助,于是将系列文章翻译过来!在自我提高的过程中,也希望对同道中人有所帮助.作者Brett Beaure ...
- 利用VisualSVN修改配置库名称
相信大家都听说过SVN的大名,至于它的用途以及如何安装不在本文范围内,这里主要讲解如何利用VisualSVN来更改配置库的名称,前提是你的SVN服务必须用VisualSVN搭建,网上几乎没有这方面的文 ...
- Docker 安装运行MySQL
1.镜像主页 https://hub.docker.com/_/mysql 2.拉取5.7版本 docker pull mysql:5.7 3.或者拉取最新8.x版本 docker pull mysq ...