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

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

传统的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. Vue 资源

    一. 资源教程 综合类 vuejs 英文资料 Vue中文资料总汇 Vue.js 的一些资源索引 vue资料 入门类 vue 快速入门 Vue.js 中文系列视频教程 on Laravist 英文教程 ...

  2. 03 xml封装通信接口

    <?php class Response_xml{ /** *按xml方式输出通信 *@param integet $code 状态码 *@param string $message 提示信息 ...

  3. python中if __name__ == '__main__': 的解析(转载)

    当你打开一个.py文件时,经常会在代码的最下面看到if __name__ == '__main__':,现在就来介 绍一下它的作用. 模块是对象,并且所有的模块都有一个内置属性 __name__.一个 ...

  4. Linux 中权限的再讨论( 下 )

    前言 上篇随笔讲述了Linux中权限的大致实现机制以及目录权限的相关规则.本文将讲解Linux中的三种特殊权限:SUID,SGID,Sticky权限.看完这两篇文章,你一定会对Linux的权限有个更深 ...

  5. DotNetBar MessageBoxEx 显示中文 显示office2007风格

    MessageBoxEx显示消息的时候按钮是中文的解决这个问题设置 MessageBoxEx的UseSystemLocalizedString属性为 true. MessageBoxEx.UseSys ...

  6. css常用总结

    1.固定一个层在页面的位置,不受滚动条影响, 属性position:fixed,如: .tbar{ height:200px;width:60px;background-color:#666;posi ...

  7. EasyDarwin开源流媒体服务器提供的TS切片/HLS直播打包库

    EasyHLS  Github:https://github.com/EasyDarwin/EasyHLS EasyHLS是什么? EasyHLS是EasyDarwin开源流媒体社区开发的一款HLS打 ...

  8. java XML-RPC

    1.XML-RPC简介 xml rpc是使用http协议做为传输协议的rpc机制,使用xml文本的方式传输命令和数据.一个rpc系统,必然包括2个部分:1.rpc client,用来向rpc serv ...

  9. javascript Date对象的介绍及linux时间戳如何在javascript中转化成标准时间格式

    1.Date对象介绍 Date对象具有多种构造函数.new Date()new Date(milliseconds)new Date(datestring)new Date(year, month)n ...

  10. (转)findViewById 返回为null (自定义控件)

    一.自定义控件 findViewById返回为null 首先讲一个具体的问题,这几天在做demo时,写了一个自定义组合控件,最后在run的时候显示这两行报错.原先还以为是setOnClickListe ...