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 ...
随机推荐
- The Vertica Analytic Database:C-Store 7 Years Later笔记
1.设计目标 Vertica数据库可以说是7年之后的C-Store,在2012年发表的这样一篇论文,描述了现在基于C-Store的一部分改进,当然,Vertica借鉴了很多C-Store的思想,但并非 ...
- JS中let和var的区别
js中let和var定义变量的区别 let变量之前没见过,刚遇到,探探究竟. 以下转自:http://blog.csdn.net/nfer_zhuang/article/details/48781 ...
- Anaconda3 安装报错 bunzip2: command not found
报错信息 Anaconda3-5.3.1-Linux-x86_64.sh: line 353: bunzip2: command not found tar: This does not look l ...
- Use gdb attach pid and debug it
- 数组的filter用法
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素. 语法:var new_array = arr.filter(callback(element[, index[, a ...
- 【Paper Reading】Deep Supervised Hashing for fast Image Retrieval
what has been done: This paper proposed a novel Deep Supervised Hashing method to learn a compact si ...
- 用pycharm运行django项目
[点击]run -> Edit Configrations 弹出如下页面 点击“+” 点击Django server 在弹出页面的host填0.0.0.0 点击这个“文件夹” 点击‘+’后填下面 ...
- [luogu] P3294 [SCOI2016]背单词 (贪心)
题目描述 Lweb 面对如山的英语单词,陷入了深深的沉思,"我怎么样才能快点学完,然后去玩三国杀呢?".这时候睿智的凤老师从远处飘来,他送给了 Lweb 一本计划册和一大缸泡椒,他 ...
- JS中Math函数基础
Math 是数学函数,但又属于对象数据类型 typeof Math => ‘object’
- 06001_NoSQL概述
1.什么是NoSQL? NoSQL(NoSQL=Not Only SQL),意即“不仅仅是SQL”,是一项全新的数据库理念,泛指非关系型的数据库. 2.关于关系型数据库和nosql数据库 (1)关系型 ...