>[更多资源和教程请关注公众号:**非科班的科班**。
如果觉得我写的还可以请给个赞,谢谢大家,你的鼓励是我创作的动力](https://blog.csdn.net/qq_43255017)
## 3.SpringBoot整合Servlet

## 3.1.方式一

步骤:

- 写一个类MyFirstServlet继承HttpServlet,并重写doGet方法。
- 在类的上面用@WebServlet标识Servlet并指明name和urlPatterns。
- 在标识有@SpringBootApplication的主类上加上@ServletComponentScan。

FirstServlet.java

```
package com.example.servlet.myservlet;

import javax.servlet.http.HttpServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*SpringBoot整合Servlet方式一
*@WebServlet(name="MyFirstServlet",urlPatterns="/myFirst")相当于如下:
*
*<servlet>
* <servlet-name>MyFirstServlet</servlet-name>
* <servlet-class>ah.szxy.servlet.FirstServlet</servlet-class>
*</servlet>
*<servlet-mapping>
* <servlet-name>MyFirstServlet</servlet-name>
* <url-pattern>/first</url-pattern>
*</servlet-mapping>
*
*/

@WebServlet(name="MyFirstServlet",urlPatterns="/myFirst")
public class FirstServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("MyFirstServlet init............");
}
}
```

ServletApplication.java

```
package com.example.servlet;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class ServletApplication {

public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}

}
```

然后启动项目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204090016647.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)

最后在浏览器输入localhost:8080/myFirstServlet,页面显示空白,在控制台打印MyFirstServlet init............

## 3.2.方式二

步骤:

- 创建一个类SecondServlet继承HttpServlet,并重写doGet方法。
- 在@SpringBootApplication标识的主类中加@Bean的一个方法。
SecondServlet.java

```
package com.example.servlet.myservlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* 整合Servlet的第二种方式
*/
public class SecondServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("MySecondServlet init..........");
}
}
```

ServletApplication.java

```
package com.example.servlet;

import com.example.servlet.myservlet.SecondServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
//@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class ServletApplication {

public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}

/**
* 整合Servlet的第二种方式,创建ServletRegistrationBean并添加路径
* @return
*/
@Bean
public ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/mySecond");
return bean;
}
```

然后启动项目,在浏览器中访问localhost:8080/mySecondServlet,页面也是空白,在控制台就会打印MySecondServlet init..........
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204085950721.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)
项目,结构如图所示
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204085945535.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)

结论:

- 上面的两种方式推荐使用第一种基于注解的整合。
- 虽然现在几乎用不到servlet了,但是学习SpringBoot整合servlet有助于学习的深入了解,更好的理解框架。

## 4.SpringBoot整合Filter

## 4.1.方式一

步骤:

- 创建一个MyFirstFilter类实现Filter接口,并在类上面标注@WebFilter。
- 在@SpringBootApplication的主类上加上@ServletComponentScan注解。

MyFirstFilter.java

```
package com.example.servlet.myfilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
* 基于@WebFilter注解整合Filter方式一
*/
@WebFilter(filterName = "MyFirstFilter",urlPatterns = "/myFirst")
public class MyFirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
System.out.println("进入Filter中了.....");
arg2.doFilter(arg0,arg1);
System.out.println("离开Filter了.......");
}

@Override
public void destroy() {

}
}
```

ServletApplication.java

```
package com.example.servlet;

import com.example.servlet.myservlet.SecondServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class ServletApplication {

public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}

/**
* 整合Servlet的第二种方式,创建ServletRegistrationBean并添加路径
* @return
*/
@Bean
public ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/mySecond");
return bean;
}
}
```

## 4.2.方式二

步骤:

- 创建一个类MySecondFilter实现Filter接口,重写方法。
- 在@SpringBootApplication标识的主类中加@Bean的一个方法,将MySecondFilter对象注入容器中。

MySecondFilter.java

```
package com.example.servlet.myfilter;

import javax.servlet.*;
import java.io.IOException;

/**
* 整合Filter的第二种方式
*/
public class MySecondFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
System.out.println("进入MySecondFilter了......");
arg2.doFilter(arg0, arg1);
System.out.println("离开MySecondFilter了......");
}

@Override
public void destroy() {

}
}
```

ServletApplication.java

```
package com.example.servlet;

import com.example.servlet.myfilter.MySecondFilter;
import com.example.servlet.myservlet.SecondServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
//@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class ServletApplication {

public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}

/**
* 整合Filter的第二种方式
* 注册Filter
*/
@Bean
public FilterRegistrationBean getFilterRegistrationBean() {
FilterRegistrationBean bean = new FilterRegistrationBean(new MySecondFilter());
// bean.addUrlPatterns(new String[]{"*.do","*.jsp"});//拦截多个时
bean.addUrlPatterns("/mySecond");
return bean;
}
}
```

然后在浏览器访问localhost:8080/mySecond,就可以看到控制台打印如下
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204085637336.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)
## 5.SpringBoot整合Listener

## 5.1.方式一

步骤:

- 创建一个类MyFirstListener实现ServletContextListener接口,重写方法
- 在该类上加上@WebListener注解

```
package com.example.servlet.mylistener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
* springBoot 整合Listener第一种方式
* 创建一个Servlet上下文的监听器
* @WebListener 自动注册,相当于在web.xml中添加如下代码
*
*<listener>
* <listener-class>ah.szxy.listener.FirstListener</listener-class>
*</listener>
*/
@WebListener
public class MyFirstListener implements ServletContextListener {

@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("MyFirstListener执行销毁了。。。");
}

@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("MyFirstListener执行初始化了。。。");
}
}
```

执行项目会打印如下,因为用了@ServletComponentScan注解,在项目启动的时候就会扫描包中是否含有servlet,若有就初始化。由于FirstServlet是基于注解初始化的,所以在项目启动的时候,就会执行初始化servlet,被Listener监听到
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204085543689.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)

## 5.1.方式二

步骤:

- 创建一个类MySecondListener实现ServletContextListener接口,重写方法。
- 在@SpringBootApplication标识的主类中加@Bean的一个方法,将MySecondListener对象注入容器中。

```
package com.example.servlet.mylistener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
* 整合Listener的第二种方式
*/
public class MySecondListener implements ServletContextListener {

@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("MySecondListener执行销毁了。。。");
}

@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("MySecondListener执行初始化了。。。");
}

}
```

```
package com.example.servlet;

import com.example.servlet.myfilter.MySecondFilter;
import com.example.servlet.mylistener.MySecondListener;
import com.example.servlet.myservlet.SecondServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class ServletApplication {

public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}

/**
* 注册listener
*/
@Bean
public ServletListenerRegistrationBean<MySecondListener> getServletListenerRegistrationBean() {
ServletListenerRegistrationBean<MySecondListener> bean = new ServletListenerRegistrationBean<MySecondListener>(
new MySecondListener());
return bean;
}

}
```

执行项目,在控制台可以看到输出如下,两个Servlet监听器都执行了
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204085523947.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)
总的项目目录包结构如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191204085518613.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjU1MDE3,size_16,color_FFFFFF,t_70)
>[更多资源和教程请关注公众号:**非科班的科班**。
如果觉得我写的还可以请给个赞,谢谢大家,你的鼓励是我创作的动力](https://blog.csdn.net/qq_43255017)

SpringBoot整合三大组建(Servlet、Listener、Filter)的更多相关文章

  1. springboot扫描自定义的servlet和filter代码详解_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 这几天使用spring boot编写公司一个应用,在编写了一个filter,用于指定编码的filter,如下: /** ...

  2. JavaEE--JavaWeb三大组件Servlet、Filter、Listener

    Servlet.Filter.Listener是JavaEE Web服务规定的服务器动态组件,由开发者编写由Web容器创建,并保证单例以及线程安全性,其中加载顺序为Linstener -> Fl ...

  3. servlet,listener,filter,interceptor的关系

    1.servlet:servlet是一种运行服务器端的java应用程序,具有独立于平台和协议的特性,并且可以动态的生成web页面,它工作在客户端请求与服务器响应的中间层.最早支持 Servlet 技术 ...

  4. 18. Spring Boot 、注册Servlet三大组件Servlet、Filter、Listener

    由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件 public class MyServlet extends ...

  5. SpringBoot初始教程之Servlet、Filter、Listener配置(七)

    1.介绍 通过之前的文章来看,SpringBoot涵盖了很多配置,但是往往一些配置是采用原生的Servlet进行的,但是在SpringBoot中不需要配置web.xml的 因为有可能打包之后是一个ja ...

  6. SpringBoot初始教程之Servlet、Filter、Listener配置

    1.介绍通过之前的文章来看,SpringBoot涵盖了很多配置,但是往往一些配置是采用原生的Servlet进行的,但是在SpringBoot中不需要配置web.xml的 因为有可能打包之后是一个jar ...

  7. SpringBoot初始教程之Servlet、Filter、Listener配置详解

    1.介绍 通过之前的文章来看,SpringBoot涵盖了很多配置,但是往往一些配置是采用原生的Servlet进行的,但是在SpringBoot中不需要配置web.xml的 因为有可能打包之后是一个ja ...

  8. SpringBoot(四)-- 整合Servlet、Filter、Listener

    SpringBoot中有两种方式可以添加 Servlet.Filter.Listener. 1.代码注册 通过ServletRegistrationBean. FilterRegistrationBe ...

  9. springboot(3):整合Servlet,filter,listener

    1.springboot整合Servlet(2种方式) 添加maven依赖:spring-boot-starter-web 1>通过注解扫描完成Servlet组件的注册(方式1) 步骤:需要3步 ...

随机推荐

  1. LeetCode3_无重复字符的最长子串(数组&字符串问题)

    题目: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "ab ...

  2. CentOS系统将UTC时间修改为CST时间方法

    世界协调时间(Universal Time Coordinated,UTC): GPS 系统中有两种时间区分,一为UTC,另一为LT(地方时)两者的区别为时区不同,UTC就是0时区的时间,地方时为本地 ...

  3. 使用element的upload组件实现一个完整的文件上传功能(上)

    说到标题就有点心塞了,前段时间项目上需要实现一个文件上传的功能,然后就咔咔的去用了element的upload组件,不用不知道一用吓一跳哇. 在使用的过程中遇到了很多让意想不到的问题,后来也因为时间问 ...

  4. 深入JVM(二)JVM概述

    深入JVM(一)JVM指令手册 深入JVM(二)JVM概述 一.JVM的原理 Java虚拟机是Java平台的基石,解决了硬件和操作系统的相互独立性.不同平台(Windows,Linux和MacOS)的 ...

  5. 服务发现之eureka

    一.什么是服务发现? 问题: 我们现在有多少个服务? 服务越来越多时,服务 URL 配置管理变得非常乱 服务对外的地址变了,其他所有有使用到的服务都要改地址 增加服务,增加服务实例等,都要做运维工作 ...

  6. 一篇长文说 git 基础

    版本管理在产品级开发中是非常重要的一个部分,它涉及到团队协作,且影响到产品最终的发布.上线以及测试环节,当前最流行的版本控制系统是 git.git 内容非常多,本文尽量克制地来介绍 git 的基础内容 ...

  7. CPP 设计模式学习

    源地址 https://www.ev0l.art/index.php/archives/20/ 备忘录模式 在一个类内部记录另一个类的快照状态的模式.可以再合适的时候跳回复用 设计备忘录的三大步骤: ...

  8. MyBatis原理-拦截器

    一.MyBatis拦截器介绍 MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能. MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用.默认情况下,M ...

  9. 02_小程序——onPageScroll 你入坑了吗?

    1:你的 onPageScroll 事件是不是失灵?闲话不多说,直接上代码!!! <!--pages/homePage/testing/testing.wxml--> <view c ...

  10. ssh免密登陆和加密解密

    一 丶实现无密码的远程管理 1.生成公钥 私钥 [root@room9pc14 桌面]# ssh-keygen [root@room9pc14 桌面]# ls /root/.ssh/ 2.上传公钥到虚 ...