一、环境

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. 数据结构之递归Demo(走迷宫)(八皇后)(汉诺塔)

    递归 顾名思义,递归就是递归就是递归就是递归就是递归......就是递归 Google递归:

  2. P1666前缀单词

    题目传送门点我传送 Ⅰ.字典树+树型DP 非常奇妙的一种解法 第一部分:构建树 先对来的单词读入,插入字典树 然后对于一颗字典树,其实是有很多无用边的,所以我们需要删去一些边 删去非单词节点和非单词节 ...

  3. 线段树 G - Mayor's posters 小技巧

    G - Mayor's posters POJ - 2528 这个题目要倒着来写,从后面往前面贴,因为前面的有些会被后面的覆盖. 所以我们就判断这张海报的位置有没有完全被覆盖,如果完全被覆盖了就不能贴 ...

  4. mybatis添加信息自动生成主键

    一.使用Oracle数据库 举例:添加员工的时候自动生成主键 1.在dao接口中声明方法 2.在mapper中实现该方法 需要先在数据表中创建序列 3.测试 注意:在调用过save方法之后,emp对象 ...

  5. Spring Cloud学习 之 Spring Cloud Ribbon 重试机制及超时设置不生效

    今天测了一下Ribbon的重试跟超时机制,发现进行的全局超时配置一直不生效,配置如下: ribbon: #单位ms,请求连接的超时时间,默认1000 ConnectTimeout: 500 #单位ms ...

  6. Matlab中 awgn 函数输入参数带有‘measured’ 时snr的含义

    MATLAB中awgn 函数可以为输入信号x 添加一定大小的噪声. out = awgn(in,snr,'measured');  是一种常见的使用方法,意思是在添加噪声前先测量一下输入信号的功率,再 ...

  7. FZU2105 线段树 (按位操作)

    题目: Given N integers A={A[0],A[1],...,A[N-1]}. Here we have some operations: (元素和操作元素 < 16) Opera ...

  8. HDU 2016 (水)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2016 题目大意:给你 n 个数,把最小的数和第一个数字互换,然后输出 解题思路: 很水,开数组,遍历并 ...

  9. Redis学习笔记(十) 客户端

    Redis服务器是典型的一对多服务器程序:一个服务器可以与多个客户端建立网络连接,每个客户端可以向服务器发送命令请求,而服务器则接收并处理客户端发送的命令请求,并向客户端返回命令回复. 通过使用由I/ ...

  10. jQuery的面试题

    1.$的原理 答案: 1)$("选择器")是先查找DOM元素,再将DOM元素放入jQuery对象中 其中自带优化: 如果选择器是#id,则自动调用getElementById 如果 ...