zoukankan      html  css  js  c++  java
  • (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

  • 相关阅读:
    【玩转微信公众平台之二】 账号注冊
    SharePoint 2010 Form Authentication (SQL) based on existing database
    淘宝API学习之道:淘宝API相关了解
    Java中Map的使用
    ROADS+dijkstra的灵活运用+POJ
    Jquery Ajax时 error处理 之 parsererror
    P1719 最大加权矩形
    回文串
    P1816 忠诚
    P1725 琪露诺
  • 原文地址:https://www.cnblogs.com/javasl/p/11918182.html
Copyright © 2011-2022 走看看