(020)Spring Boot之Servlet过滤器(Filter)监听器(Listener)

Posted 明月之诗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(020)Spring Boot之Servlet过滤器(Filter)监听器(Listener)相关的知识,希望对你有一定的参考价值。

  分别有两种方法实现Servlet、过滤器(Filter)、监听器(Listener)

  先贴出pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.edu.spring</groupId>
    <artifactId>springboot_web</artifactId>
    <version>1.0.0</version>

    <name>springboot_web</name>
    <!-- FIXME change it to the project\'s website -->
    <url>http://www.example.com</url>
    <parent> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-parent</artifactId> 
        <version>2.0.4.RELEASE</version> 
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>
View Code

  方法一,使用注解,(WebServlet、WebFilter、WebListener是Servlet3.0的注解)

  (1)Servlet使用@ServletComponentScan+@WebServlet。举例如下:

  UserServlet.java

package com.edu.spring.springboot;

import java.io.IOException;

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

@WebServlet("/user.do")
public class UserServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().print("user servlet");
    }
}
View Code

  App.java

package com.edu.spring.springboot;

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

@ServletComponentScan
@SpringBootApplication
public class App 
{
    public static void main(String[] args) {
         SpringApplication.run(App.class, args);
    }
}
View Code

  浏览器输入:http://127.0.0.1:8080/user.do,验证结果如下:

   (2)Filter使用@ServletComponentScan+@WebFilter。举例如下:

  LogFilter.java

package com.edu.spring.springboot;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("/user.do")
public class LogFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        // TODO Auto-generated method stub
        System.out.println("income log filter "+arg0.getRemoteHost());
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
View Code

  App.java

package com.edu.spring.springboot;

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

@ServletComponentScan
@SpringBootApplication
public class App 
{
    public static void main(String[] args) {
         SpringApplication.run(App.class, args);
    }
}
View Code

  浏览器输入:http://127.0.0.1:8080/user.do,验证结果如下:

   (3)Listener使用@ServletComponentScan+@WebListener。举例如下:

  MyContextListener.java

package com.edu.spring.springboot;

import java.time.LocalDateTime;

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

@WebListener
public class MyContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        System.out.println("start at "+LocalDateTime.now().toString());
    }

}
View Code

  App.java

package com.edu.spring.springboot;

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

@ServletComponentScan
@SpringBootApplication
public class App 
{
    public static void main(String[] args) {
         SpringApplication.run(App.class, args);
    }
}
View Code

  启动结果如下:

   方法二,分别创建3个bean:ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean

  servlet对应ServletRegistrationBean;Filter对应FilterRegistrationBean;Listenner对应ServletListenerRegistrationBean。请看代码:

  UserServlet.java

package com.edu.spring.springboot;

import java.io.IOException;

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

@WebServlet("/user.do")
public class UserServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().print("user servlet");
    }
}
View Code

  LogFilter.java

package com.edu.spring.springboot;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("/user.do")
public class LogFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        // TODO Auto-generated method stub
        System.out.println("income log filter "+arg0.getRemoteHost());
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
View Code

  MyContextListener.java

package com.edu.spring.springboot;

import java.time.LocalDateTime;

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

@WebListener
public class MyContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        System.out.println("start at "+LocalDateTime.now().toString());
    }

}
View Code

  ServletConfig.java。创建bean,并且装配到spring容器中

package com.edu.spring.springboot;

import java.util.Arrays;

import org.springframework.boot.SpringBootConfiguration;
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;

@SpringBootConfiguration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean createBookServlet(){
        ServletRegistrationBean servlet= new ServletRegistrationBean(new UserServlet(),"/user.do");
        return servlet;
    }
    
    @Bean
    public FilterRegistrationBean createEchoFilter(){
        FilterRegistrationBean filter=new FilterRegistrationBean();
        filter.setFilter(new LogFilter());
        filter.setUrlPatterns(Arrays.asList("/user.do"));
        return filter;
    }
    
    @Bean
    public ServletListenerRegistrationBean<MyContextListener> createStartedUpListener(){
        ServletListenerRegistrationBean<MyContextListener> servletRegistrationBean=new ServletListenerRegistrationBean(new MyContextListener());
        return servletRegistrationBean;
    }
}
View Code

  App.java

package com.edu.spring.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App 
{
    public static void main(String[] args) {
         SpringApplication.run(App.class, args);
    }
}
View Code

  启动并验证结果如下:

   浏览器输入:http://127.0.0.1:8080/user.do ,验证Servlet

   验证Filter

 

 

 

 

 

以上是关于(020)Spring Boot之Servlet过滤器(Filter)监听器(Listener)的主要内容,如果未能解决你的问题,请参考以下文章

spring boot基础之servlet3.0和spring4.x零配置相关文章

Spring Boot实战之Filter实现简单的Http Basic认证

怎么改spring boot http port

(34)java Spring Cloud+Spring boot+mybatis企业快速开发架构之SpringCloud-Zuul过滤器介绍及使用(传递数据拦截请求和异常处理)

Spring Boot 之Application.properties配置大全

从零一起学Spring Boot之LayIM项目长成记 初见 Spring Boot