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

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

传统的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即可生效。

@SpringBootApplication@ServletComponentScanpublic 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中配置那么直观,不过也是挺简单的。

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

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

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

相关文章:
【推荐】 大数据、数据挖掘在交通领域的应用
【推荐】 微服务实践沙龙-上海站
【推荐】 扫脸动画

Spring Boot 学习系列(08)—自定义servlet、filter及listener的更多相关文章

  1. Spring Boot 实战:如何自定义 Servlet Filter

    1.前言 有些时候我们需要在 Spring Boot Servlet Web 应用中声明一些自定义的 Servlet Filter来处理一些逻辑.比如简单的权限系统.请求头过滤.防止 XSS 攻击等. ...

  2. Spring Boot 学习系列(05)—自定义视图解析规则

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 自定义视图解析 在默认情况下Spring Boot 的MVC框架使用的视图解析ViewResolver类是C ...

  3. Spring Boot 学习系列(09)—自定义Bean的顺序加载

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

  4. Spring Boot 学习系列(10)—SpringBoot+JSP的使

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 解决问题 随着spring boot 框架的逐步使用,我们期望对于一些已有的系统进行改造,做成通用的脚手架, ...

  5. Spring Boot 学习系列(03)—jar or war,做出你的选择

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 两种打包方式 采用Spring Boot框架来构建项目,我们对项目的打包有两种方式可供选择,一种仍保持原有的 ...

  6. Spring boot 学习笔记 1 - 自定义错误

    Spring Boot提供了WebExceptionHandler一个以合理的方式处理所有错误的方法.它在处理顺序中的位置就在WebFlux提供的处理程序之前,这被认为是最后一个处理程序. 对于机器客 ...

  7. Spring Boot 学习系列(06)—采用log4j2记录日志

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 为什么选择log4j2 log4j2相比于log4j1.x和logback来说,具有更快的执行速度.同时也支 ...

  8. Spring Boot 学习系列(07)—properties文件读取

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 传统的properties读取方式 一般的,我们都可以自定义一个xxx.properties文件,然后在工程 ...

  9. Spring Boot 学习系列(01)—从0到1,只需两分钟

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 快速构建 如果我们想基于spring mvc 提供一个简单的API查询服务,传统的方式,首先需要我们引入sp ...

随机推荐

  1. HDU 5145 NPY and girls (莫队分块离线)

    题目地址:HDU 5145 莫队真的好奇妙.. 这种复杂度竟然仅仅有n*sqrt(n)... 裸的莫队分块,先离线.然后按左端点分块,按块数作为第一关键字排序.然后按r值作为第二关键字进行排序. 都是 ...

  2. Excel表格数据导入Mysql数据库的方法

    1.使用Navicat 连接需要导入的数据库. 2.excel 列的名字最好和数据库的名字一致,便于我们直观的查看好理解.   第一步,先创建好表,和准备好对应的excel文件.在Navicat 中选 ...

  3. 如何获取ipa 包的图片

    突然想起当初刚学习iOS的时候,就经常通过抓包和提取素材的方式来模仿App,今天就教大家如何一步步提取App的素材! 大家是否有过想要获取别人的素材的想法?看到某些App的资源很不错,很想导出来用用, ...

  4. 初识kbmmw 中的smartbind功能

    关于kbmmw smartbind 的开发原因及思路,大家可以参见官方的博客说明和红鱼儿的翻译. 今天我就实例操作一下,给大家演示一下具体实现. 我们新建一个工程 放几个基本的控件 在单元里面加上引用 ...

  5. src/github.com/mongodb/mongo-go-driver/mongo/cursor.go 游标的简洁实用

    src/github.com/mongodb/mongo-go-driver/mongo/cursor.go // Copyright (C) MongoDB, Inc. 2017-present./ ...

  6. Spring 实战 学习笔记(1)

    Spring的核心 依赖注入 & 切面编程 1.创建应用组件之间协作的行为通常称为装配.(wiring) 2.Spring EL表达式.SEL是一种能在运行时构建复杂表达式,存取对象属性.对象 ...

  7. (转)基于RTP的H264视频数据打包解包类

    最近考虑使用RTP替换原有的高清视频传输协议,遂上网查找有关H264视频RTP打包.解包的文档和代码.功夫不负有心人,找到不少有价值的文档和代码.参考这些资料,写了H264 RTP打包类.解包类,实现 ...

  8. Vue实战指南之依赖注入(provide / inject)

    案例 UI美眉说咱家的选项菜单太丑了,小哥哥能不能美化一下呀,洒家自然是说小意思啦~自定义一个select组件,so easy~ 简单粗暴型: <el-select v-model=" ...

  9. BZOJ 2002 Bounce 弹飞绵羊 —— 分块算法

    题目链接:https://vjudge.net/problem/HYSBZ-2002 2002: [Hnoi2010]Bounce 弹飞绵羊 Time Limit: 10 Sec  Memory Li ...

  10. 安装Nginx四层负载均衡

    Nginx1.9开始支持tcp层的转发,通过stream实现的,而socket也是基于tcp通信. stream模块默认不安装的,需要手动添加参数:–with-stream,官方下载地址:downlo ...