Spring Boot 学习系列(08)—自定义servlet、filter及listener
此文已由作者易国强授权网易云社区发布。
欢迎访问网易云社区,了解更多网易技术产品运营经验。
传统的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的更多相关文章
- Spring Boot 实战:如何自定义 Servlet Filter
1.前言 有些时候我们需要在 Spring Boot Servlet Web 应用中声明一些自定义的 Servlet Filter来处理一些逻辑.比如简单的权限系统.请求头过滤.防止 XSS 攻击等. ...
- Spring Boot 学习系列(05)—自定义视图解析规则
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 自定义视图解析 在默认情况下Spring Boot 的MVC框架使用的视图解析ViewResolver类是C ...
- Spring Boot 学习系列(09)—自定义Bean的顺序加载
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. Bean 的顺序加载 有些场景中,我们希望编写的Bean能够按照指定的顺序进行加载.比如,有UserServ ...
- Spring Boot 学习系列(10)—SpringBoot+JSP的使
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 解决问题 随着spring boot 框架的逐步使用,我们期望对于一些已有的系统进行改造,做成通用的脚手架, ...
- Spring Boot 学习系列(03)—jar or war,做出你的选择
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 两种打包方式 采用Spring Boot框架来构建项目,我们对项目的打包有两种方式可供选择,一种仍保持原有的 ...
- Spring boot 学习笔记 1 - 自定义错误
Spring Boot提供了WebExceptionHandler一个以合理的方式处理所有错误的方法.它在处理顺序中的位置就在WebFlux提供的处理程序之前,这被认为是最后一个处理程序. 对于机器客 ...
- Spring Boot 学习系列(06)—采用log4j2记录日志
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 为什么选择log4j2 log4j2相比于log4j1.x和logback来说,具有更快的执行速度.同时也支 ...
- Spring Boot 学习系列(07)—properties文件读取
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 传统的properties读取方式 一般的,我们都可以自定义一个xxx.properties文件,然后在工程 ...
- Spring Boot 学习系列(01)—从0到1,只需两分钟
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 快速构建 如果我们想基于spring mvc 提供一个简单的API查询服务,传统的方式,首先需要我们引入sp ...
随机推荐
- Mac 怎么打开两个终端
把光标移到终端上,然后Command+N 启动maven : mvn tomcat7:run
- mac osx 下编译 OpenWrt
默认的文件系统hfs大小写不敏感.新建一个磁盘镜像文件并合式化为hfs+, 然后挂载到系统中. hdiutil create -size 20g -fs "Case-sensitive HF ...
- 阿里云 访问控制RAM
https://help.aliyun.com/product/28625.html 为用户分配最小权限 别名主要用于 RAM 用户登录以及成功登录后的显示名. 强烈建议您给主账号绑定多因素认证. 设 ...
- java UUID的解析与应用(转载)
原文链接:http://www.blogjava.net/feelyou/archive/2008/10/14/234320.html 讨论UUID的定义.分类.应用及生成工具. 什么是UUID? U ...
- 多媒体开发之---h.264 SPS PPS解析源代码,C实现一以及nal分析器
http://blog.csdn.net/mantis_1984/article/details/9465909 http://blog.csdn.net/arau_sh/article/detail ...
- POJ 2263 Heavy Cargo(ZOJ 1952)
最短路变形或最大生成树变形. 问 目标两地之间能通过的小重量. 用最短路把初始赋为INF.其它为0.然后找 dis[v]=min(dis[u], d); 生成树就是把最大生成树找出来.直到出发和终点能 ...
- Android-通过SlidingMenu高仿微信6.2最新版手势滑动返回(二)
转载请标明出处: http://blog.csdn.net/hanhailong726188/article/details/46453627 本文出自:[海龙的博客] 一.概述 在上一篇博文中,博文 ...
- RTSP流媒体转发服务器源码
最新EasyDarwin已经支持海康.大华等标准RTSP/RTP协议的转发,代码及使用方法参看:用Darwin开发RTSP级联服务器(拉模式转发)http://blog.csdn.net/xiejia ...
- gdb coredump的使用
1 出现core dump时最好的办法是使用gdb查看coredump文件 2 使用的条件 出现问题的代码,系统,所有涉及的代码都应该一起编译,然后得到符号表,这样加载符号表,使用coredump文件 ...
- mongodb学习之:GridFS
GridFS是一种在Mongodb中存储大二进制文件的机制.GridFS 用于存储和恢复那些超过16M(BSON文件限制)的文件(如:图片.音频.视频等). 使用GridFS有如下几个原因: 1 利用 ...