springboot学习系列(08)—自定义servletfilter及listener

tianshidan1998      2022-04-17     758

关键词:

此文已由作者易国强授权网易云社区发布。

欢迎访问网易云社区,了解更多网易技术产品运营经验。

传统的filter及listener配置

  • 在传统的Java web项目中,servlet、filter和listener的配置很简单,直接在web.xml中按顺序配置好即可,程序启动时,就会按照你配置的顺序依次加载(当然,web.xml中各配置信息总的加载顺序是context-param -> listener -> filter -> servlet),项目搭建完成后,估计一般新来的开发同学没啥事都不会去关注里面都做了些啥~ = =

  • 废话少说,上代码,下面是一个传统的web.xml配置示例。

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- define charset --><filter>
    <filter-name>Set UTF-8</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param></filter><servlet>
    <servlet-name>silver</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:xxx-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>
    <servlet-name>silver</servlet-name>
    <url-pattern>/</url-pattern></servlet-mapping>

Spring Boot中该如何配置?

  • 需要说明的是,Spring Boot项目里面是没有web.xml的,那么listener和filter我们该如何配置呢?

  • 在Spring Boot项目中有两种方式进行配置,一种是通过Servlet3.0+提供的注解进行配置,分别为@WebServlet、@WebListener、@WebFilter。示例如下:

import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException;/**
 * @author bjyiguoqiang
 * @date 2017/11/9 17:28.
 */@WebFilter(urlPatterns = "/*", filterName = "helloFilter")public class HelloFilter implements Filter {    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init helloFilter");
    }    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter helloFilter");
        filterChain.doFilter(servletRequest,servletResponse);

    }    @Override
    public void destroy() {

    }
}
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/**
 * @author bjyiguoqiang
 * @date 2017/11/9 17:27.
 */@WebServlet(name = "hello",urlPatterns = "/hello")public class HelloServlet extends HttpServlet {    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("hello word");
        resp.getWriter().flush();
        resp.getWriter().close();
    }    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doGet(req, resp);
    }
}
import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;/**
 * @author bjyiguoqiang
 * @date 2017/11/9 17:28.
 */@WebListenerpublic class HelloListener implements ServletContextListener {    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("HelloListener contextInitialized");
    }    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
  • 最后在程序入口类加入扫描注解@ServletComponentScan即可生效。

@[email protected] class DemoaApplication {    public static void main(String[] args) {
        SpringApplication.run(DemoaApplication.class, args);
    }
}
  • 需要注意的是,使用@WebFilter 是无法实现filter的过滤顺序的,使用org.springframework.core.annotation包中的@Order注解在spring boot环境中也是不支持的。所有如果需要对自定义的filter排序,那么可以采用下面所述的方式。

  • 另一种配置则是通过Spring Boot提供的三种类似Bean实现的,分别为ServletRegistrationBean、ServletListenerRegistrationBean以及FilterRegistrationBean。使用示例分别如下:

import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/**
 * @author bjyiguoqiang
 * @date 2017/11/9 17:44.
 */@Configurationpublic class MyConfigs {    /**
     * 配置hello过滤器
     */
    @Bean
    public FilterRegistrationBean sessionFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new HelloFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.addInitParameter("session_filter_key", "session_filter_value");
        registrationBean.setName("helloFilter");        //设置加载顺序,数字越小,顺序越靠前,建议最小从0开始配置,最大为Integer.MAX_VALUE
        registrationBean.setOrder(10);        return registrationBean;
    }    /**
     * 配置hello Servlet
     */
    @Bean
    public ServletRegistrationBean helloServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new HelloServlet());
        registration.addUrlMappings("/hello");        //设置加载顺序,数字越小,顺序越靠前,建议最小从0开始配置,最大为Integer.MAX_VALUE
        registration.setOrder(3);        return registration;
    }    /**
     * 配置hello Listner
     */
    @Bean
    public ServletListenerRegistrationBean helloListenerRegistrationBean(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new HelloListener());        //设置加载顺序,数字越小,顺序越靠前,建议最小从0开始配置,最大为Integer.MAX_VALUE
        servletListenerRegistrationBean.setOrder(3);        return servletListenerRegistrationBean;
    }
}
  • 通过Bean注入的方式进行配置,可以自定义加载顺序,这点很nice。

    最后

  • 在Spring Boot的环境中配置servlet、filter和listener虽然没有在web.xml中配置那么直观,不过也是挺简单的。

  • 不足之处,欢迎指正,谢谢~


免费体验云安全(易盾)内容安全、验证码等服务


更多网易技术、产品、运营经验分享请点击




相关文章:
【推荐】 网站规划通识:原型图绘制的一些注意事项










springboot学习系列(09)—自定义bean的顺序加载

此文已由作者易国强授权网易云社区发布。欢迎访问网易云社区,了解更多网易技术产品运营经验。Bean的顺序加载有些场景中,我们希望编写的Bean能够按照指定的顺序进行加载。比如,有UserServiceBean和OrderServiceBean,我们需要在Or... 查看详情

springboot学习系列(09)—自定义bean的顺序加载

此文已由作者易国强授权网易云社区发布。欢迎访问网易云社区,了解更多网易技术产品运营经验。Bean的顺序加载有些场景中,我们希望编写的Bean能够按照指定的顺序进行加载。比如,有UserServiceBean和OrderServiceBean,我们需要在Or... 查看详情

springboot学习笔记自定义starter(代码片段)

springBoot学习笔记(四)自定义starter自定义starter自定义zdy-spring-boot-starter编写simpleBeanMyAutoConfiguration注解EnableRegisterServer配置标记类ConfigMarker创建/META-INF/spring.factories结果展示自定义starterstarter机制Sp 查看详情

springboot系列——自定义异常反馈

〇、原始的异常反馈  当出现4xx或5xx错误时,springboot项目返回的原始异常反馈是如下风格。   一、指定异常页面  1.ErrorMvcAutoConfiguration  按照SpringBoot的惯例,默认的配置都在xxxAutoConfiguration类中。而异常处理则在Er... 查看详情

android自定义view系列笔记收录

...自己的同时分享给他人,欢迎批评指正。在这里把我学习的有关Android自定义View之后写的笔记和看过的文章收录一下,把自己学到的知识点总结一下。PS:下面把学习过并在文章里面有讲解的知识点打✔,不了解和文章... 查看详情

springcloud系列之自定义gatewayfilterfactory(代码片段)

SpringCloud系列之自定义GatewayFilterFactory学习目的:知道创建一个网关sample知道网关的基本配置知道自定义GatewayFilterFactory类环境准备:JDK1.8SpringBoot2.2.3SpringCloud(Hoxton.SR7)Maven3.2+开发工具IntelliJIDEAsmartGit新增SpringBootInitializer项目:N 查看详情

springboot系列之自定义枚举类的数据校验注解

SpringBoot系列之自定义枚举类的数据校验注解业务场景:数据校验,需要对枚举类型的数据传参,进行数据校验,不能随便传参。拓展,支持多个参数的枚举数据校验在网上找到很多参考资料,所以本博客基于这些博客进行拓展... 查看详情

springboot系列配置文件详解

...定义数据配置1.通过prefix2.通过@value注解获取 引言:Springboot有一个全局配置文件,这个配置文件默认是properties文件,就是application.properties文件,其实还有一种文件 查看详情

springboot学习05-自定义错误页面完整分析

 Springboot学习06-自定义错误页面完整分析前言   接着上一篇博客,继续分析Springboot错误页面问题正文 1-自定义浏览器错误页面(只要将自己的错误页面放在指定的路径下即可) 1-1-Springboot错误页面匹配机制(以404... 查看详情

springboot学习-自定义starter

自己开发一个springbootstarter的步骤1.新建一个项目(全部都基于maven),比如新建一个spring-boot-starter-redis的maven项目pom.xml:1<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 查看详情

springboot框架学习7-springboot的web开发-自定义消息转换器

...章节主要内容:通过前面的学习,我们了解并快速完成了springboot第一个应用。springboot企业级框架,那么springboot怎么读取静态资源?如js文件夹,css文件以及png/jpg图片呢?怎么自定义消息转换器呢?怎么自定义springmvc的配置呢?... 查看详情

saltstack学习系列之自定义grains

Master端打开存放自定义grains的目录vim/etc/salt/masterfile_roots:base:-/srv/salt/建立自定义模块cd/srv/saltmkdir_grainscd_grains编写自定义grainscatdisk.pyimportosdefdisk():grains={}disk=os.popen(‘fdisk-l|grep‘Disk‘|grep-v‘ 查看详情

springboot框架学习8-干货springboot的web开发-自定义拦截器处理权限

...章节主要内容:通过前面的学习,我们了解并快速完成了springboot第一个应用。springboot企业级框架,那么springboot怎么读取静态资源?如js文件夹,css文件以及png/jpg图片呢?怎么自定义消息转换器呢?怎么自定义springmvc的配置呢?... 查看详情

springboot框架学习3-springboot核心

...nner3:全局配置文件本文是《凯哥陪你学系列-框架学习之springboot框架学习》中第三篇springboot框架学习3-springboot核心(2)声明:本文系凯哥Java(www.kaigejava.com)原创,未经允许,禁止转载!一:怎么手动关闭不需要的配置?在上一篇中,... 查看详情

vue学习系列--自定义指令

前面的章节我们先后学习了v-on、v-bind、v-model、v-link等内置指令,今天我们就来学习一下如何创建自定义指令。自定义指令也是先注册后使用,其注册和组件的注册很类似,也分为全局注册和局部注册。只是注册组件... 查看详情

自定义view系列一自定义view的构造函数,自定义属性(代码片段)

...是一道坎.虽然说是坎但是也得走过去的!此系列文章作为学习自定义View的一系列学习笔记.在进入学习自定义View的殿堂, 查看详情

vulkan系列教程—vma教程—用户自定义内存池(代码片段)

...列教程,定时更新,请大家关注。如果需要深入学习Vulkan的同学,可以点击课程链接,学习链接Vulkan学习群:594715138腾讯课堂:《Vulkan原理与实战—铸造渲染核武器—基石篇》网易课堂:《Vulkan原理与... 查看详情

vulkan系列教程—vma教程—用户自定义内存池(代码片段)

...列教程,定时更新,请大家关注。如果需要深入学习Vulkan的同学,可以点击课程链接,学习链接Vulkan学习群:594715138腾讯课堂:《Vulkan原理与实战—铸造渲染核武器—基石篇》网易课堂:《Vulkan原理与... 查看详情