SpringBoot学习笔记(6)----SpringBoot中使用Servlet,Filter,Listener的三种方式
在一般的运用开发中Controller已经大部分都能够实现了,但是也不排除需要自己实现Servlet,Filter,Listener的方式,SpringBoot提供了三种实现方式。
1. 使用Bean的实现方式
首先创建一个Servlet,一个Filter,一个Listener,
DemoServlet.java
package com.wangx.boot.util.servlet; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class DemoServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get method");
doPost(req,resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post method");
resp.getWriter().write("hello world");
}
}
DemoFilter.java
package com.wangx.boot.util.filter; import javax.servlet.*;
import java.io.IOException; public class DemoFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException { } @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("开始拦截了....");
} @Override
public void destroy() { }
}
DemoListener.java
package com.wangx.boot.util.listener; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; public class DemoListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("contextInitialized");
} @Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("contextDestroyed");
}
}
然后直接在SpringBoot的启动类中将上面几个方法注册为Bean,
SpringBootDemo01Application.java
package com.wangx.boot; import com.wangx.boot.util.filter.DemoFilter;
import com.wangx.boot.util.listener.DemoListener;
import com.wangx.boot.util.servlet.DemoServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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; @SpringBootApplication
public class SpringBootDemo01Application { /**
* 注册Servlet
* @return
*/
@Bean
public ServletRegistrationBean createServlet () {
//第二个参数为urlPartern
return new ServletRegistrationBean(new DemoServlet(), "/demoServlet");
} /**
* 注册Filter
* @return
*/
@Bean
public FilterRegistrationBean createFilter() {
//第二个参数为需要拦截的路径,不传则拦截所有
return new FilterRegistrationBean(new DemoFilter(), createServlet());
} /**
* 注册Listener
* @return
*/
@Bean
public ServletListenerRegistrationBean createrListener() {
//自定义个Listener.监听整个Context的Servlet
return new ServletListenerRegistrationBean(new DemoListener());
} public static void main(String[] args) {
SpringApplication.run(SpringBootDemo01Application.class, args);
}
}
启动项目时会Listener会打印contextInitialized,关闭时会打印contextDestroyed,访问时拦截器打印"开始拦截了....",并成功访问到Servlet,并输入hello world到浏览器上。
2. 实现ServletContextInitializer接口
直接在SpringBoot的启动类中实现ServletContextInitializer,重写onStartup()方法也可以使用Servlet.Filter,Listener,以上面三个Demo类为例,使用ServletContextInitializer的方式的代码:
package com.wangx.boot; import com.wangx.boot.util.filter.DemoFilter;
import com.wangx.boot.util.listener.DemoListener;
import com.wangx.boot.util.servlet.DemoServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletContextInitializer; import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet; @SpringBootApplication
public class SpringBootDemo01Application implements ServletContextInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemo01Application.class, args);
} @Override
public void onStartup(ServletContext servletContext) throws ServletException {
//创建Servlet,并映射访问路径为demoServlet
servletContext.addServlet("demoServlet", new DemoServlet()).addMapping("/demoServlet");
//创建Filter,拦截的Servlet
servletContext.addFilter("demoFilter", new DemoFilter()).addMappingForServletNames(EnumSet.of(DispatcherType.FORWARD), true, "demoServlet"); //创建Listener servletContext.addListener(new DemoListener()); } }
运行结果与1相同
3. 使用注解的方式
这是一个SpringBoot官方推荐的方式,也是三种方式中最简单的方式,只需要在SpringBoot的启动类上添加@ServletComponentScan注解,在DemoServlet类上添加@WebServlet(name = "demoServlet", urlPatterns = "/demoServlet")注解,DemoFilter类上添加@WebFilter(urlPatterns = "/*", dispatcherTypes = DispatcherType.FORWARD)(拦截所有请求),DemoListener类上添加@WebListener即可,运行结果与1相同。
SpringBoot学习笔记(6)----SpringBoot中使用Servlet,Filter,Listener的三种方式的更多相关文章
- 转 Velocity中加载vm文件的三种方式
Velocity中加载vm文件的三种方式 velocitypropertiespath Velocity中加载vm文件的三种方式: 方式一:加载classpath目录下的vm文件 Prope ...
- Velocity中加载vm文件的三种方式
Velocity中加载vm文件的三种方式: a. 加载classpath目录下的vm文件 /** * 初始化Velocity引擎 * --VelocityEngine是单例模式,线程安全 * @th ...
- SpringBoot学习笔记(6) SpringBoot数据缓存Cache [Guava和Redis实现]
https://blog.csdn.net/a67474506/article/details/52608855 Spring定义了org.springframework.cache.CacheMan ...
- spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。
在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的 ...
- Action 中获取表单数据的三种方式
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/53138905 冷血之心的博客) Action 中获取表单提交数据 ...
- vue中通过路由跳转的三种方式
原文:https://blog.csdn.net/qq_40072782/article/details/82533477 router-view 实现路由内容的地方,引入组件时写到需要引入的地方需要 ...
- Maven中解决jar包冲突的三种方式
首先我们在idea中创建一个maven工程,我们只关注pom.xml以及External Libraries中导入的jar包 导入spring-beans.jar <dependency> ...
- SpringBoot学习笔记(5)----SpringBoot中异常处理的三种方法
对于异常的处理,Spring Boot中提供默认的一个异常处理界面,如下图: 但是在实际的运用开发中,这样的页面显然是不友好的,Spring Boot也提供了自定义异常处理的方式,如下总结三种一场处理 ...
- Hibernate学习笔记2.5(Hibernate核心开发接口和三种状态)
1.configuration(配置信息管理,产生sessionfactory) sessionfactory管理一系列的连接池 opensession 永远打开新的,需要手动close getcur ...
随机推荐
- [Reading] Asking while Reading
Asking while Reading ——读Java垃圾收集器与内存分配策略 Java与C++之间有一堵由内存动态分配和垃圾收集技术所围成的“高墙”,墙外面的人想进去,墙里面的人却想出来. 为什么 ...
- ZBrush中遮罩的概念及使用
刚接触设计软件的小伙伴有可能不知道什么叫做遮罩,遮罩的概念是什么,顾名思义,遮罩就是可以将局部进行遮挡,使用它可以锁定和保护我们不想改变的模型位置,即被遮罩的部分将不参与任何编辑. ZBrush®软件 ...
- python之类与对象的属性
类相关的知识 在python2中的区分: 经典类: class School: pass 新式类: class School(object): pass 在python3中以上两种均为新式类 属性: ...
- EXGSBS模板
EXBSGS模板 我之前把有一处b和c弄反了,有点困...然后调了半天 (exbsgs比excrt简单多了) 求x的最小正整数解 原式子拆成 在bsgs中,保证a,b互质,这样求出的逆元挪过去才对 但 ...
- [LUOGU]P3701 主席树(假的)
有人恶意刷难度...就一个最大流模板... 但是题面吼啊2333 #include <iostream> #include <cstdio> #include <queu ...
- django-1-框架介绍
<<<python虚拟环境>>> 用django框架做web开发必须要用到python虚拟环境,而且一个虚拟环境只能创建一个django项目,如果创建多个djang ...
- 2019-03-15 使用Request POST获取CNABS网站上JSON格式的表格数据,并解析出来用xlwt写到Excel中
import requests import xlwt url = 'https://v1.cn-abs.com/ajax/ChartMarketHandler.ashx' headers={ 'Us ...
- javascript-js常用插件集合
area.js 中国地区分级的js代码 Scripts/crypto.js CryptoJS (crypto.js) 为 JavaScript 提供了各种各样的加密算法 ...
- maven 构建web项目
Maven规定,必须创建以下几个Source Folder src/main/resources src/main/Java src/test/resources src/test/java 添加以上 ...
- [using_microsoft_infopath_2010]Chapter2 表单需求,使用表决矩阵
本章概要 1.从模板创建表单 2.从创建表单收集需求 3.使用全部表单决策 4.决定需要创建哪种表单