一、环境

1.1、Idea 2020.1

1.2、JDK 1.8

二、步骤

2.1、点击File -> New Project -> Spring Initializer,点击next

2.2、在对应地方修改自己的项目信息

2.3、选择Web依赖,选中Spring Web。可以选择Spring Boot版本,本次默认为2.2.6,点击Next

2.4、项目结构

三、自定义实现

3.1、通过bean实现

新建
CustomListener.java
package org.ouyushan.springboot.custom.servlet.config.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; /**
* @Description: 自定义监听器
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:45
*/
public class CustomListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("========contextInitialized========");
} @Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("========contextDestroyed========");
}
}

CustomFilter.java
package org.ouyushan.springboot.custom.servlet.config.filter;

import javax.servlet.*;
import java.io.IOException; /**
* @Description: 自定义fileter
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:38
*/
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("========init filter========");
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("========do filter========");
filterChain.doFilter(servletRequest, servletResponse);
} @Override
public void destroy() {
System.out.println("========destroy filter========");
}
}
CustomServlet.java
package org.ouyushan.springboot.custom.servlet.config.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* @Description: 自定义servlet
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:25
*/
public class CustomServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("========servlet get method is called========");
resp.getWriter().write("hello world by get");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("========servlet post method is called========");
resp.getWriter().write("hello world by post");
}
}
ServletController
package org.ouyushan.springboot.custom.servlet.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* @Description:
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:55
*/
@RestController
@RequestMapping("/api")
public class ServletController { @RequestMapping("/servlet")
public String servlet() {
return "custom servlet";
} @RequestMapping("/filter")
public String filter() {
return "custom filter";
}
}
在启动类中装载自定义bean
package org.ouyushan.springboot.custom.servlet;

import org.ouyushan.springboot.custom.servlet.config.filter.CustomFilter;
import org.ouyushan.springboot.custom.servlet.config.listener.CustomListener;
import org.ouyushan.springboot.custom.servlet.config.servlet.CustomServlet;
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 SpringBootCustomServletApplication { @Bean
public ServletRegistrationBean servletRegistrationBean() {
// 只有路径是以/custom/servlet开始的才会触发
return new ServletRegistrationBean(new CustomServlet(), "/custom/servlet");
} @Bean
public FilterRegistrationBean filterRegistrationBean() {
//第二个参数为需要拦截的路径,不传则拦截所有
return new FilterRegistrationBean(new CustomFilter(), servletRegistrationBean());
} @Bean
public ServletListenerRegistrationBean<CustomListener> servletListenerRegistrationBean() {
return new ServletListenerRegistrationBean<CustomListener>(new CustomListener());
} public static void main(String[] args) {
SpringApplication.run(SpringBootCustomServletApplication.class, args);
} }
启动主程序,控制台打印:
========contextInitialized========
========init filter========

访问:
返回:
custom servlet 
控制台无自定义信息打印
通过自定义的servlet urlMapping访问:
返回:
hello world by get
控制台打印:
========do filter========
========servlet get method is called========
服务停止,控制台打印:
========destroy filter========
========contextDestroyed========

3.2、通过实现ServletContextInitializer实现

// 方式二 通过实现ServletContextInitializer
@SpringBootApplication
public class SpringBootCustomServletApplication implements ServletContextInitializer { @Override
public void onStartup(ServletContext servletContext) {
// 创建Servlet,并映射访问路径为/custom/servlet
servletContext.addServlet("customServlet", new CustomServlet()).addMapping("/custom/servlet"); // 创建Filter,拦截的Servlet
servletContext.addFilter("customFilter", new CustomFilter())
.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "customServlet"); // 设置自定义filter
servletContext.addListener(new CustomListener());
} public static void main(String[] args) {
SpringApplication.run(SpringBootCustomServletApplication.class, args);
}
}
启动主程序,控制台打印:
========contextInitialized========
========init filter========

访问:
返回:
custom servlet

控制台无自定义信息打印
 
通过自定义的servlet urlMapping访问:
返回:
hello world by get
控制台打印:
========do filter========
========servlet get method is called========
服务停止,控制台打印:
========destroy filter========
========contextDestroyed========

3.3、通过@ServletComponentScan结合注解实现

修改启动类
@ServletComponentScan
@SpringBootApplication
public class SpringBootCustomServletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCustomServletApplication.class, args);
}
}

通过添加注解修改自定义的servlet、filter、listener类
package org.ouyushan.springboot.custom.servlet.config.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* @Description: 自定义servlet
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:25
*/ @WebServlet(name = "customServlet", urlPatterns = "/custom/servlet")
public class CustomServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("========servlet get method is called========");
resp.getWriter().write("hello world by get");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("========servlet post method is called========");
resp.getWriter().write("hello world by post");
}
} package org.ouyushan.springboot.custom.servlet.config.filter; import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException; /**
* @Description: 自定义fileter
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:38
*/ @WebFilter(filterName = "customFilter", urlPatterns = "/*")
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
System.out.println("========init filter========");
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("========do filter========");
filterChain.doFilter(servletRequest, servletResponse);
} @Override
public void destroy() {
System.out.println("========destroy filter========");
}
} package org.ouyushan.springboot.custom.servlet.config.listener; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener; /**
* @Description: 自定义监听器
* @Author: ouyushan
* @Email: ouyushan@hotmail.com
* @Date: 2020/4/28 10:45
*/
@WebListener
public class CustomListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("========contextInitialized========");
} @Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("========contextDestroyed========");
}
}

启动主程序,控制台打印:
========contextInitialized========
========init filter========

访问:
返回:
custom servlet

控制台打印
========do filter========
通过自定义的servlet urlMapping访问:
返回:
hello world by get
控制台打印:
========do filter========
========servlet get method is called========

服务停止,控制台打印:
========destroy filter========
========contextDestroyed========

Spring boot Sample 006之spring-boot-custom-servlet的更多相关文章

  1. Spring boot Sample 012之spring-boot-web-upload

    一.环境 1.1.Idea 2020.1 1.2.JDK 1.8 二.目的 spring boot 整合web实现文件上传下载 三.步骤 3.1.点击File -> New Project -& ...

  2. Spring boot Sample 0010之spring-boot-web-freemarker

    一.环境 1.1.Idea 2020.1 1.2.JDK 1.8 二.目的 spring boot 整合freemarker模板开发web项目 三.步骤 3.1.点击File -> New Pr ...

  3. Spring boot Sample 009之spring-boot-web-thymeleaf

    一.环境 1.1.Idea 2020.1 1.2.JDK 1.8 二.目的 spring boot 整合thymeleaf模板开发web项目 三.步骤 3.1.点击File -> New Pro ...

  4. Spring boot Sample 005之spring-boot-profile

    一.环境 1.1.Idea 2020.1 1.2.JDK 1.8 二.目的 通过yaml文件配置spring boot 属性文件 三.步骤 3.1.点击File -> New Project - ...

  5. Spring Boot (五)Spring Data JPA 操作 MySQL 8

    一.Spring Data JPA 介绍 JPA(Java Persistence API)Java持久化API,是 Java 持久化的标准规范,Hibernate是持久化规范的技术实现,而Sprin ...

  6. 一起学JAVA之《spring boot》03 - 开始spring boot基本配置及项目结构(转)

    <div class="markdown_views"> <h3 id="一导航"><a name="t0"& ...

  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 cloud教程之使用spring boot创建一个应用

    <7天学会spring cloud>第一天,熟悉spring boot,并使用spring boot创建一个应用. Spring Boot是Spring团队推出的新框架,它所使用的核心技术 ...

  9. Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...

随机推荐

  1. 学习Vue第四节,v-model和双向数据绑定

    Vue指令之v-model和双向数据绑定 <!DOCTYPE html> <html> <head> <meta charset="utf-8&qu ...

  2. tp5中使用ueditor编辑器保存文本到数据库后回显后显示html标签问题解决办法

    在编辑器ueditor中获取文本,保存到到数据库后为 当在数据库中提取出来,在显示回ueditor编辑器时候,出了问题, html标签都显示出来了 百度了下别人的解决办法是,使用官方提供的api 可是 ...

  3. LeetCode--LinkedList--83.Remove Duplicates from Sorted List(Easy)

    题目地址https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 83. Remove Duplicates from Sor ...

  4. RabbitMQ的发布订阅模式(Publish/Subscribe)

    一.发布/订阅(Publish/Subscribe)模式 发布订阅是我们经常会用到的一种模式,生产者生产消息后,所有订阅者都可以收到.RabbitMQ的发布/订阅模型图如下: 1.该模式下生产者并不是 ...

  5. 推荐 10个 NB的 IDEA 插件,开发效率至少提升一倍

    友情提示:插件虽好,可不要贪装哦,装多了会 卡 .卡 .卡 ~ 正经干活用的 分享一点自己工作中得心应手的IDEA插件,可不是在插件商店随随便便搜的,都经过实战检验,用过的都说好.可能有一些大家用过的 ...

  6. 简单的Java实现Netty进行通信

    使用Java搭建一个简单的Netty通信例子 看过dubbo源码的同学应该都清楚,使用dubbo协议的底层通信是使用的netty进行交互,而最近看了dubbo的Netty部分后,自己写了个简单的Net ...

  7. Flutter RenderBox指南——绘制篇

    本文基于1.12.13+hotfix.8版本源码分析. 0.大纲 RenderBox的用法 通过RenderObjectWidget把RenderBox塞进界面 1.RenderBox 在flutte ...

  8. 手机APP自动化环境搭建

    1 摘要 近年来,随着移动应用从数量上和逻辑复杂程度上的增长,以及产品发布周期的紧缩,使得回归测试迫在眉睫,鉴于此APP自动化测试变得越来流行,当前主流的APP自动化工具有:Appium.Roboti ...

  9. class.getFields和class.getDeclareFields的区别

    class.getFields的定义 返回类提供的public域包括超类的共有变量; 注: 是public,我们平时定义变量一般用的private,如果用getFields是不会获得. class.g ...

  10. 5.2 Go 包与函数

    5.2 Go 包与函数 在多个包中相互调用函数,需要用到Go包的知识. 代码组织如下: 思路: 1.定义功能函数calc放入到utils.go,将utils.go放在utils文件夹/包中,当其他文件 ...