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 ...
随机推荐
- linux新建文件和文件夹命令
1.touch命令 touch命令用来修改文件的访问时间.修改时间.如果没有指定时间,则将文件时间属性改为当前时间. 当指定文件不存在,touch命令变为创建该文件. 语法: touch [-acm] ...
- Android Material Design 中文版
http://www.google.com/design/spec/animation/authentic-motion.html http://www.oschina.net/question/14 ...
- 【原创】Sublime Text 3快捷配置c++的编译,运行,gdb环境
打开Tools ->Build System -> New Build System 弹出一个文件,将原有的东西删掉,输入: { "encoding": "u ...
- 原来浏览器原生支持JS Base64编码解码 outside of the Latin1 range
原来浏览器原生支持JS Base64编码解码 « 张鑫旭-鑫空间-鑫生活 https://www.zhangxinxu.com/wordpress/2018/08/js-base64-atob-bto ...
- 什么是aop?-------转
什么是AOP? http://www.cnblogs.com/zhugenqiang/archive/2008/07/27/1252761.html#commentform(转) AOP(Aspec ...
- java 浮点数
package precisenumber; //import java.util.*;public class PreciseNumber { public int fore; public int ...
- 利用AutoLayout适配滚动视图和表视图
1.新增一个contentView,设置为与滑动视图的父视图等高等宽. 2.利用代码 if(_MyTestTableView.frame.size.height != _MyTestTableView ...
- iOS 9已下的获取APP进程信息
- (NSDictionary *)getAppInfo:(NSString *)exec withBundleID:(NSString *)bundle { if ([exec isKindOfCl ...
- codeforces 715c
题目大意:给定一个有N个点的树,问其中有多少条路径满足他们的边权连成的数对M取余为0.其中gcd(M,10)=1. 题解: 很亲民的点分治题目,对每一层点分治,预处理每个点到当前根的数字并对m取余,和 ...
- Java 递归算法,遍历文件夹下的所有文件。
用递归算法遍历文件下的所有子文件夹和子文件 文件夹遍历方法 public void getFileList(String strPath){ File f=new File(strPath); try ...