源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all

一、说明

1.1 项目结构说明

  1. 项目提供与servlet整合的两种方式,一种是servlet3.0 原生的注解方式,一种是采用spring 注册的方式;
  2. servlet、过滤器、监听器分别位于servlet、filter、listen 下,其中以Annotation命名结尾的代表是servlet注解方式实现,采用spring注册方式则在ServletConfig中进行注册;
  3. 为了说明外置容器对servlet注解的自动发现机制,项目采用外置容器构建,关于spring boot 整合外置容器的详细说明可以参考spring-boot-tomcat

1.2 项目依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--排除依赖 使用外部tomcat容器启动-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <!--使用外置容器时候SpringBootServletInitializer 依赖此包 -->
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!--servlet api 注解依赖包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
    </dependencies>

二、采用spring 注册方式整合 servlet

2.1 新建过滤器、监听器和servlet

/**
 * @author : heibaiying
 * @description : 自定义过滤器
 */

public class CustomFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setAttribute("filterParam","我是filter传递的参数");
        chain.doFilter(request,response);
        response.getWriter().append(" CustomFilter ");
    }

    @Override
    public void destroy() {

    }
}
/**
 * @author : heibaiying
 * @description : 自定义监听器
 */
public class CustomListen implements ServletContextListener {

    //Web应用程序初始化过程正在启动的通知
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("容器初始化启动");
    }

    /* 通知servlet上下文即将关闭
     * 这个地方如果我们使用的是spring boot 内置的容器 是监听不到销毁过程,所以我们使用了外置 tomcat 容器
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("容器即将销毁");
    }
}
/**
 * @author : heibaiying
 * @description : 自定义servlet
 */
public class CustomServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet 执行:" + req.getAttribute("filterParam"));
        resp.getWriter().append("CustomServlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.2 注册过滤器、监听器和servlet

/**
 * @author : heibaiying
 */
@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean registrationBean() {
        return new ServletRegistrationBean<HttpServlet>(new CustomServlet(), "/servlet");
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean<Filter>();
        bean.setFilter(new CustomFilter());
        bean.addUrlPatterns("/servlet");
        return bean;
    }

    @Bean
    public ServletListenerRegistrationBean listenerRegistrationBean() {
        return new ServletListenerRegistrationBean<ServletContextListener>(new CustomListen());
    }

}

三、采用注解方式整合 servlet

3.1 新建过滤器、监听器和servlet,分别使用@WebFilter、@WebListener、@WebServlet注解标注

/**
 * @author : heibaiying
 * @description : 自定义过滤器
 */

@WebFilter(urlPatterns = "/servletAnn")
public class CustomFilterAnnotation implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request,response);
        response.getWriter().append(" CustomFilter Annotation");
    }

    @Override
    public void destroy() {

    }
}
/**
 * @author : heibaiying
 * @description :自定义监听器
 */
@WebListener
public class CustomListenAnnotation implements ServletContextListener {

    //Web应用程序初始化过程正在启动的通知
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("容器初始化启动 Annotation");
    }

    /* 通知servlet上下文即将关闭
     * 这个地方如果我们使用的是spring boot 内置的容器 是监听不到销毁过程,所以我们使用了外置 tomcat 容器
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("容器即将销毁 Annotation");
    }
}
/**
 * @author : heibaiying
 * @description : 自定义servlet
 */
@WebServlet(urlPatterns = "/servletAnn")
public class CustomServletAnnotation extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("CustomServlet Annotation");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3.2 使注解生效

  1. 如果是内置容器,需要在启动类上添加@ServletComponentScan(“com.heibaiying.springbootservlet”) ,指定扫描的包目录;
  2. 如果是外置容器,不需要进行任何配置,依靠容器内建的discovery机制自动发现,需要说明的是这里的容器必须支持servlet3.0(tomcat从7.0版本开始支持Servlet3.0)。

附:源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all

spring boot 2.x 系列 —— spring boot 整合 servlet 3.0的更多相关文章

  1. spring boot 2.x 系列 —— spring boot 整合 redis

    文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...

  2. spring boot 2.x 系列 —— spring boot 整合 druid+mybatis

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.说明 1.1 项目结构 项目查询用的表对应的建表语句放置在resour ...

  3. spring boot 2.x 系列 —— spring boot 整合 kafka

    文章目录 一.kafka的相关概念: 1.主题和分区 2.分区复制 3. 生产者 4. 消费者 5.broker和集群 二.项目说明 1.1 项目结构说明 1.2 主要依赖 二. 整合 kafka 2 ...

  4. spring boot 2.x 系列 —— spring boot 整合 dubbo

    文章目录 一. 项目结构说明 二.关键依赖 三.公共模块(boot-dubbo-common) 四. 服务提供者(boot-dubbo-provider) 4.1 提供方配置 4.2 使用注解@Ser ...

  5. spring boot 2.x 系列 —— spring boot 整合 RabbitMQ

    文章目录 一. 项目结构说明 二.关键依赖 三.公共模块(rabbitmq-common) 四.服务消费者(rabbitmq-consumer) 4.1 消息消费者配置 4.2 使用注解@Rabbit ...

  6. spring boot 2.x 系列 —— spring boot 实现分布式 session

    文章目录 一.项目结构 二.分布式session的配置 2.1 引入依赖 2.2 Redis配置 2.3 启动类上添加@EnableRedisHttpSession 注解开启 spring-sessi ...

  7. Spring 5.x 、Spring Boot 2.x 、Spring Cloud 与常用技术栈整合

    项目 GitHub 地址:https://github.com/heibaiying/spring-samples-for-all 版本说明: Spring: 5.1.3.RELEASE Spring ...

  8. Spring Boot 2.X(十):自定义注册 Servlet、Filter、Listener

    前言 在 Spring Boot 中已经移除了 web.xml 文件,如果需要注册添加 Servlet.Filter.Listener 为 Spring Bean,在 Spring Boot 中有两种 ...

  9. 2018年分享的Spring Cloud 2.x系列文章

    还有几个小时2018年就要过去了,盘点一下小编从做做公众号以来发送了273篇文章,其中包含原创文章90篇,虽然原创的有点少,但是2019年小编将一如既往给大家分享跟多的干货,分享工作中的经验,让大家在 ...

随机推荐

  1. 双目相机标定以及立体测距原理及OpenCV实现

    单目相机标定的目标是获取相机的内参和外参,内参(1/dx,1/dy,Cx,Cy,f)表征了相机的内部结构参数,外参是相机的旋转矩阵R和平移向量t.内参中dx和dy是相机单个感光单元芯片的长度和宽度,是 ...

  2. 简明Python3教程 5.第一步

    介绍 我们现在来看看如何在Python中运行传统的”Hello world”程序.这会教你如何写.保存以及运行Python程序. 有两种办法来运行您的Python程序——使用交互式的解释器提示符或者源 ...

  3. Codeforces Round #160 (Div. 2)---A. Roma and Lucky Numbers

    Roma and Lucky Numbers time limit per test 1 second memory limit per test 256 megabytes input standa ...

  4. WPF旋转的界面实现

    原文:WPF旋转的界面实现 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/yangyisen0713/article/details/1821534 ...

  5. ehcache hibernate4整合问题

    当在原有hibernate使用ehcache缓存的项目中加入ehcache时,报如下错误时 Caused by: org.hibernate.service.spi.ServiceException: ...

  6. 构建自己的PHP框架(ORM)

    完整项目地址:https://github.com/Evai/Aier 我们选择 Laravel 的 illuminate/database 作为我们的 ORM 包. 在本系列教程里,每一个 Comp ...

  7. WPF实现选项卡效果(2)——动态添加AvalonDock选项卡

    原文:WPF实现选项卡效果(2)--动态添加AvalonDock选项卡 简介 在前面一篇文章里面,我们使用AvalonDock实现了类似于VS的选项卡(或者浏览器的选项卡)效果.但是我们是通过xaml ...

  8. EF context.SaveChanges()特点

    EF context.SaveChanges()特点 1 一次连接保存多条数据(工作单元模式): 2 内部通过事务来执行,如果一条数据保存失败,执行回滚操作: 3 延时加载 var userList= ...

  9. 一步一步造个IoC轮子(一):IoC是什么

    一步一步造个Ioc轮子目录 一步一步造个IoC轮子(一):IoC是什么 一步一步造个IoC轮子(二):详解泛型工厂 一步一步造个IoC轮子(三):构造基本的IoC容器 前言 .net core正式版前 ...

  10. delphi备份恢复剪切板(使用了GlobalLock API函数和CopyMemory)

    看了季世平老兄的C++代码后翻译过来的 unit clipbak; interface uses SysUtils, Classes, Clipbrd, Windows, Contnrs; type ...