上一篇我们学习了 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;
}
  • 运行测试。

访问:http://localhost:8080/a

 
测试

注解注册

  • 创建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;
} }
  • 运行测试。

访问:http://localhost:8080/b

 
测试

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的更多相关文章

  1. Spring Boot整合Servlet,Filter,Listener,访问静态资源

    目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...

  2. spring boot:多个filter/多个interceptor/多个aop时设置调用的先后顺序(spring boot 2.3.1)

    一,filter/interceptor/aop生效的先后顺序? 1,filter即过滤器,基于servlet容器,处于最外层, 所以它会最先起作用,最后才停止 说明:filter对所有访问到serv ...

  3. spring boot整合servlet、filter、Listener等组件方式

    创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...

  4. Spring Boot 注册 Servlet 的三种方法,真是太有用了!

    本文栈长教你如何在 Spring Boot 注册 Servlet.Filter.Listener. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spr ...

  5. spring boot配置Servlet容器

    Spring boot 默认使用Tomcat作为嵌入式Servlet容器,只需要引入spring-boot-start-web依赖,默认采用的Tomcat作为容器 01  定制和修改Servlet容器 ...

  6. ServletContextInitializer添加 servlet filter listener

    ServletContextInitializer添加 servlet filter listener https://www.cnblogs.com/pomer-huang/p/9639322.ht ...

  7. [转] Spring Boot实战之Filter实现使用JWT进行接口认证

    [From] http://blog.csdn.net/sun_t89/article/details/51923017 Spring Boot实战之Filter实现使用JWT进行接口认证 jwt(j ...

  8. SpringBoot学习笔记(6)----SpringBoot中使用Servlet,Filter,Listener的三种方式

    在一般的运用开发中Controller已经大部分都能够实现了,但是也不排除需要自己实现Servlet,Filter,Listener的方式,SpringBoot提供了三种实现方式. 1. 使用Bean ...

  9. SpringBoot---注册Servlet,Filter,Listener

    1.概述 1.1.当使用  内嵌的Servlet容器(Tomcat.Jetty等)时,将Servlet,Filter,Listener  注册到Servlet容器的方法: 1.1.1.直接注册Bean ...

随机推荐

  1. android 应用签名的作用

    来源:https://www.jianshu.com/p/61206c96471a 1..应用程序升级:如果你希望用户无缝升级到新的版本,那么你必须用同一个证书进行签名.这是由于只有以同一个证书签名, ...

  2. TLS握手协议分析与理解——某HTTPS请求流量包分析

    https://xz.aliyun.com/t/1039 HTTPS简介 HTTPS,是一种网络安全传输协议,在HTTP的基础上利用SSL/TLS来对数据包进行加密,以提供对网络服务器的身份认证,保护 ...

  3. 宣化上人: 大佛顶首楞严经四种清净明诲浅释(8-9)(转自学佛网:http://www.xuefo.net/nr/article23/230825.html)

    大佛顶首楞严经四种清净明诲浅释(8) 唐天竺·沙门般剌密帝译 宣化上人主讲 一九八三年四月十七日晚讲于万佛圣城 各自谓己得上人法.詃惑无识.恐令失心.所过之处.其家耗散. 各自谓己:每一个都是自己称赞 ...

  4. 报错:Exception: org.apache.sqoop.common.SqoopException Message: DRIVER_0002:Given job is already running - Job with id 1

    报错背景: 创建完成job之后,执行job的时候报错. 报错现象: Exception: org.apache.sqoop.common.SqoopException Message: CLIENT_ ...

  5. Dockerfile-server2

    [root@lab2 docker-file]# cd server2/ [root@lab2 server2]# ls ddbes-server2-0.0.1-SNAPSHOT.jar Docker ...

  6. SUBLIME必备插件FOR PHP

    Sublime Text真是一款写代码的利器,轻巧快捷,而且功能强大,用来写PHP代码再好不过了,告别以前用的笨重臃肿的Zend Studio,感觉一身轻松,PHP代码也更加优雅.但是PHP开发也经常 ...

  7. 【opencv】opencv函数isContinuous

    isContinuous 参考 1. opencv_isContinuous; 完

  8. Python:实现图片裁剪的两种方式——Pillow和OpenCV

    原文:https://blog.csdn.net/hfutdog/article/details/82351549 在这篇文章里我们聊一下Python实现图片裁剪的两种方式,一种利用了Pillow,还 ...

  9. ajax页面刷新小错误(提交按钮type必须为button,而不能是submit)

    背景: 使用ajax提交form表单时,提交按钮的type值写为了submit,导致ajax中回调函数中的提示信息toastr.success('提交数据成功');没有执行,只执行了alert语句 , ...

  10. Terence’s Stuff: Why do we do research?

    This sound like a question best answered via a survey conducted by a body such as Vitae, an internat ...