Spring Boot Sample 006之spring-boot-custom-servlet

一、环境

  • Idea 2020.1
  • JDK 1.8
  • maven

二、目的

学习Spring Boot servlet、 filter、 listener等知识点

三、步骤

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

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

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

 3.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========

 

posted @ 2020-06-01 11:30  欧虞山  阅读(168)  评论(0编辑  收藏  举报