在一般的运用开发中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的三种方式的更多相关文章

  1. 转 Velocity中加载vm文件的三种方式

    Velocity中加载vm文件的三种方式   velocitypropertiespath Velocity中加载vm文件的三种方式:    方式一:加载classpath目录下的vm文件 Prope ...

  2. Velocity中加载vm文件的三种方式

    Velocity中加载vm文件的三种方式: a.  加载classpath目录下的vm文件 /** * 初始化Velocity引擎 * --VelocityEngine是单例模式,线程安全 * @th ...

  3. SpringBoot学习笔记(6) SpringBoot数据缓存Cache [Guava和Redis实现]

    https://blog.csdn.net/a67474506/article/details/52608855 Spring定义了org.springframework.cache.CacheMan ...

  4. spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。

    在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的 ...

  5. Action 中获取表单数据的三种方式

    (尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/53138905  冷血之心的博客) Action 中获取表单提交数据 ...

  6. vue中通过路由跳转的三种方式

    原文:https://blog.csdn.net/qq_40072782/article/details/82533477 router-view 实现路由内容的地方,引入组件时写到需要引入的地方需要 ...

  7. Maven中解决jar包冲突的三种方式

    首先我们在idea中创建一个maven工程,我们只关注pom.xml以及External Libraries中导入的jar包 导入spring-beans.jar <dependency> ...

  8. SpringBoot学习笔记(5)----SpringBoot中异常处理的三种方法

    对于异常的处理,Spring Boot中提供默认的一个异常处理界面,如下图: 但是在实际的运用开发中,这样的页面显然是不友好的,Spring Boot也提供了自定义异常处理的方式,如下总结三种一场处理 ...

  9. Hibernate学习笔记2.5(Hibernate核心开发接口和三种状态)

    1.configuration(配置信息管理,产生sessionfactory) sessionfactory管理一系列的连接池 opensession 永远打开新的,需要手动close getcur ...

随机推荐

  1. 使用CocoaPods更新第三方库出错的解决办法

    使用CocoaPods更新第三方库出错的解决办法 执行完pod install或pod update之后,控制台抛出以下警告信息: [!] The xx [Debug] target override ...

  2. java ScriptEngine 使用 (java运行脚本文件)

    转自:http://www.tuicool.com/articles/imEbQbA Java SE 6最引人注目的新功能之一就是内嵌了脚本支持.在默认情况下,Java SE 6只支持JavaScri ...

  3. DRF lazy Serializer

    class LazySerializer: def __init__(self, cls_name, **kwargs): self.cls_name = cls_name self.kwargs = ...

  4. 设置PATH 环境变量、pyw格式、命令行运行python程序与多重剪贴板

    pyw格式简介: 与py类似,我认为他们俩卫衣的不同就是前者运行时候不显示终端窗口,后者显示 命令行运行python程序: 在我学习python的过程中我通常使用IDLE来运行程序,这一步骤太过繁琐( ...

  5. Django -聚合分组,FQ操作, cookie, session

    一. 聚合查询和分组 1. 聚合 aggregate(*args, **kwargs) 对一组数据进行统计分析, 通过对QuerySet进行计算, 返回一个聚合值得字典. arrgregate()中每 ...

  6. java整型byte,short,int,long取值范围大小

     byte 1个字节 short 2个字节 int 4个字节long 8 个字节 varchar 可变长度的非Unicode数据,最长为8000个字符nvarchar 可变长度Unicode数据,最长 ...

  7. 【转】 C#获取当前程序运行路径的方法集合

    [转] C#获取当前程序运行路径的方法集合 //获取当前进程的完整路径,包含文件名(进程名). string str = this.GetType().Assembly.Location; resul ...

  8. Run Nutch In Eclipse on Linux and Windows nutch version 0.9

    Running Nutch in Eclipse Here are instructions for setting up a development environment for Nutch un ...

  9. maven小知识点

    Maven 使用惯例优于配置的原则 .它要求在没有定制之前,所有的项目都有如下的结构: 一个 maven 项目在默认情况下会产生 JAR 文件,另外 ,编译后 的 classes 会放在 basedi ...

  10. C. Amr and Chemistry(Codeforces Round #312 (Div. 2) 二进制+暴力)

    C. Amr and Chemistry time limit per test 1 second memory limit per test 256 megabytes input standard ...