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 { @Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("init helloFilter");} @Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("doFilter helloFilter");filterChain.doFilter(servletRequest,servletResponse);} @Overridepublic 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 { @Overridepublic void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().print("hello word");resp.getWriter().flush();resp.getWriter().close();} @Overrideprotected 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 { @Overridepublic void contextInitialized(ServletContextEvent servletContextEvent) {System.out.println("HelloListener contextInitialized");} @Overridepublic 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过滤器*/@Beanpublic 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_VALUEregistrationBean.setOrder(10); return registrationBean;} /*** 配置hello Servlet*/@Beanpublic ServletRegistrationBean helloServletRegistration() {ServletRegistrationBean registration = new ServletRegistrationBean(new HelloServlet());registration.addUrlMappings("/hello"); //设置加载顺序,数字越小,顺序越靠前,建议最小从0开始配置,最大为Integer.MAX_VALUEregistration.setOrder(3); return registration;} /*** 配置hello Listner*/@Beanpublic ServletListenerRegistrationBean helloListenerRegistrationBean(){ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();servletListenerRegistrationBean.setListener(new HelloListener()); //设置加载顺序,数字越小,顺序越靠前,建议最小从0开始配置,最大为Integer.MAX_VALUEservletListenerRegistrationBean.setOrder(3); return servletListenerRegistrationBean;} }
通过Bean注入的方式进行配置,可以自定义加载顺序,这点很nice。
最后
在Spring Boot的环境中配置servlet、filter和listener虽然没有在web.xml中配置那么直观,不过也是挺简单的。
不足之处,欢迎指正,谢谢~
免费体验云安全(易盾)内容安全、验证码等服务
更多网易技术、产品、运营经验分享请点击。
相关文章:
【推荐】 大数据、数据挖掘在交通领域的应用
【推荐】 微服务实践沙龙-上海站
【推荐】 扫脸动画
转载于:https://www.cnblogs.com/163yun/p/9887283.html
Spring Boot 学习系列(08)—自定义servlet、filter及listener相关推荐
- Spring Boot 学习系列(05)—自定义视图解析规则
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 自定义视图解析 在默认情况下Spring Boot 的MVC框架使用的视图解析ViewResolver类是C ...
- Spring Boot 学习系列(09)—自定义Bean的顺序加载
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. Bean 的顺序加载 有些场景中,我们希望编写的Bean能够按照指定的顺序进行加载.比如,有UserServ ...
- Spring Boot 学习系列(07)—properties文件读取
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 传统的properties读取方式 一般的,我们都可以自定义一个xxx.properties文件,然后在工程 ...
- Spring Boot 学习系列(01)—从0到1,只需两分钟
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 快速构建 如果我们想基于spring mvc 提供一个简单的API查询服务,传统的方式,首先需要我们引入sp ...
- Spring Boot 学习系列(04)—分而治之,多module打包
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 明确功能,各司其职 在一个结构清晰的项目中,一个没有module划分的结构显然不是最佳实践.有人会说可以在同 ...
- Spring Boot 学习系列(02)—使用热部署,提升开发效
此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 开发调试很简单 热部署的使用非常简单,但能极大的提高我们的开发效率,像传统的web应用,我们修改后需要重新编 ...
- Spring Boot自定义 Servlet Filter 的两种方式
点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 作者 | 码农小胖哥 来源 | 公众号「码农小胖哥」 针 ...
- 2023最新首发,全网最全 Spring Boot 学习宝典(附思维导图)
作者:bug菌 博客:CSDN.掘金.infoQ.51CTO等 简介:CSDN/阿里云/华为云/51CTO博客专家,博客之星Top30,掘金年度人气作者Top40,51CTO年度博主Top12,掘金/ ...
- Spring Boot学习笔记-基础(2)
Spring Boot学习笔记-基础(2) Spring Boot 优点: – 快速创建独立运行的Spring项目以及与主流框架集成 – 使用嵌入式的Servlet容器,应用无需打成WAR包 – st ...
最新文章
- 帮奶牛找对象?华为云AI黑科技大揭秘
- AI = “Automated Inspiration(灵感自动化)”
- 计算机房英语视频,雅思听力场景词汇:计算机房场景
- 【week3】psp (技术随笔)
- hadoop2.7之Mapper/reducer源码分析
- 矢量切片_数据粒度均衡的二维矢量瓦片构建方法
- Kali下JDK1.8的安装过程
- 网络编程--Address already in use 问题
- java 多个 panel_java – 在JFrame中组织多个JPanel的好方法是...
- php网站 只显示sinsiu_sinsiu_cms_1_0_10
- springcloud工作笔记093---springcloud封装按钮权限控制_思路和实现_根据用户拥有的权限控制是否显示某个按钮
- Ubuntu搭建嵌入式开发(交叉编译)环境-转
- python词嵌入_【自然语言处理】收藏!使用Python的4种句嵌入技术
- UVA960 Gaussian Primes【数学】
- 记录神通数据库2022安装
- 电蚊拍GB4706检测及安规测试设备
- 计算机英语课堂活动总结,英语活动总结(精选8篇)
- 数仓知识03:“自上而下“建设数仓和“自下而上“建设数仓的差异
- 下载centOS,下载各种linux版本的镜像,来这里!
- 关于JavaScript中typeof的用法