• SpringBoot(四)-- 整合Servlet、Filter、Listener


    SpringBoot中有两种方式可以添加 Servlet、Filter、Listener。

    1.代码注册

     通过ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 获得控制。

        新建WebConfig 类,用于bean的注入,内容如下:

     1 package com.xsjt.config;
     2 
     3 import java.util.ArrayList;
     4 import java.util.EventListener;
     5 import java.util.List;
     6 import org.springframework.boot.web.servlet.FilterRegistrationBean;
     7 import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
     8 import org.springframework.boot.web.servlet.ServletRegistrationBean;
     9 import org.springframework.context.annotation.Bean;
    10 import org.springframework.context.annotation.Configuration;
    11 import com.xsjt.filter.XbqFilter;
    12 import com.xsjt.listener.XbqListener;
    13 import com.xsjt.servlet.XbqServlet;
    14 
    15 /**  
    16  * ClassName:WebConfig 
    17  * 通过 @bean 注入 servlet、filter、listener
    18  * Date:     2017年11月6日 下午6:10:30
    19  * @author   Joe  
    20  * @version    
    21  * @since    JDK 1.8
    22  */
    23 @Configuration
    24 public class WebConfig {
    25 
    26     /**
    27      * servletRegistrationBean:(使用代码注册Servlet(不需要@ServletComponentScan注解)). 
    28      * @author Joe
    29      * Date:2017年11月6日下午6:13:29
    30      *
    31      * @return
    32      */
    33     @Bean
    34     public ServletRegistrationBean servletRegistrationBean(){
    35         ServletRegistrationBean registrationBean = new ServletRegistrationBean();
    36         registrationBean.setServlet(new XbqServlet());
    37         List<String> urlMappings = new ArrayList<String>();
    38         // 访问,可以添加多个
    39         urlMappings.add("/xbq/servlet");
    40         registrationBean.setUrlMappings(urlMappings);
    41         registrationBean.setLoadOnStartup(1);
    42         return registrationBean;
    43     }
    44     
    45     /**
    46      * getDemoFilter:(使用代码注册拦截器).  
    47      * @author Joe
    48      * Date:2017年11月6日下午6:17:31
    49      *
    50      * @return
    51      */
    52     @Bean
    53     public FilterRegistrationBean getDemoFilter(){
    54         XbqFilter demoFilter = new XbqFilter();
    55         FilterRegistrationBean registrationBean=new FilterRegistrationBean();
    56         registrationBean.setFilter(demoFilter);
    57         List<String> urlPatterns=new ArrayList<String>();
    58         urlPatterns.add("/*");                            //拦截路径,可以添加多个
    59         registrationBean.setUrlPatterns(urlPatterns);
    60         registrationBean.setOrder(1);
    61         return registrationBean;
    62     }
    63     
    64     /**
    65      * getDemoListener:(使用代码 引用 监听器).  
    66      * @author Joe
    67      * Date:2017年11月6日下午6:35:28
    68      *
    69      * @return
    70      */
    71     @Bean
    72     public ServletListenerRegistrationBean<EventListener> getDemoListener(){
    73         ServletListenerRegistrationBean<EventListener> registrationBean = new ServletListenerRegistrationBean<>();
    74         registrationBean.setListener(new XbqListener());
    75         registrationBean.setOrder(1);
    76         return registrationBean;
    77     }
    78 }

      其中,代码中 XbqServlet 、XbqFilter、XbqListener 代码如下:

     1 package com.xsjt.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import javax.servlet.ServletException;
     6 import javax.servlet.http.HttpServlet;
     7 import javax.servlet.http.HttpServletRequest;
     8 import javax.servlet.http.HttpServletResponse;
     9 
    10 /**  
    11  * ClassName:XbqServlet 
    12  * 通过 代码注册Servlet 
    13  * Date:     2017年11月6日 下午5:13:10
    14  * @author   Joe  
    15  * @version    
    16  * @since    JDK 1.8
    17  */
    18 public class XbqServlet extends HttpServlet{
    19 
    20     private static final long serialVersionUID = 1L;
    21 
    22     @Override
    23     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    24         this.doPost(req, resp);
    25     }
    26 
    27     @Override
    28     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    29         resp.setCharacterEncoding("UTF-8");
    30         resp.setContentType("text/html");  
    31         PrintWriter out = resp.getWriter();  
    32         out.println("<html>");  
    33         out.println("<head>");  
    34         out.println("<title>Hello World</title>");  
    35         out.println("</head>");  
    36         out.println("<body><center>");  
    37         out.println("<h3>我是通过代码注册Servlet</h3>");  
    38         out.println("</center></body>");  
    39         out.println("</html>"); 
    40     }
    41 }
    View Code
     1 package com.xsjt.filter;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.Filter;
     6 import javax.servlet.FilterChain;
     7 import javax.servlet.FilterConfig;
     8 import javax.servlet.ServletException;
     9 import javax.servlet.ServletRequest;
    10 import javax.servlet.ServletResponse;
    11 import javax.servlet.http.HttpServletRequest;
    12 import org.slf4j.Logger;
    13 import org.slf4j.LoggerFactory;
    14 
    15 /**  
    16  * ClassName:JoeFilter 
    17  * 自定义 Serlvlet 的过滤器 
    18  * Date:     2017年11月6日 下午6:01:33
    19  * @author   Joe  
    20  * @version    
    21  * @since    JDK 1.8
    22  */
    23 public class XbqFilter implements Filter {
    24     
    25     private static Logger logger = LoggerFactory.getLogger(XbqFilter.class);
    26 
    27     @Override
    28     public void init(FilterConfig filterConfig) throws ServletException {
    29         logger.info("--xbq--初始化JoeFilter!");
    30     }
    31 
    32     @Override
    33     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    34         HttpServletRequest req = (HttpServletRequest)request;
    35         logger.info(req.getRequestURL() + "---xbq---> doFilter ");
    36         chain.doFilter(request, response);
    37     }
    38 
    39     @Override
    40     public void destroy() {
    41         logger.info("--xbq--销毁JoeFilter!");
    42     }
    43 
    44 }
    View Code
     1 package com.xsjt.listener;
     2 
     3 import javax.servlet.ServletContextEvent;
     4 import javax.servlet.ServletContextListener;
     5 
     6 import org.slf4j.Logger;
     7 import org.slf4j.LoggerFactory;
     8 
     9 /**  
    10  * ClassName:JoeListener 
    11  * Date:     2017年11月6日 下午6:28:29
    12  * @author   Joe  
    13  * @version    
    14  * @since    JDK 1.8
    15  */
    16 public class XbqListener implements ServletContextListener{
    17     
    18     private static Logger logger = LoggerFactory.getLogger(XbqListener.class);
    19 
    20     @Override
    21     public void contextInitialized(ServletContextEvent sce) {
    22         logger.info("--xbq-监听器-ServletContext 初始化");
    23         logger.info(sce.getServletContext().getServerInfo());
    24     }
    25 
    26     @Override
    27     public void contextDestroyed(ServletContextEvent sce) {
    28         logger.info("--xbq-监听器-ServletContext 销毁");
    29     }
    30 }
    View Code

    2.通过注解自动注册

       在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet(urlPatterns = "/test/*")、@WebFilter、@WebListener 注解自动注册,这些注解都是JDK的,无需其他代码。

      1) Servlet

     1 package com.xsjt.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import javax.servlet.ServletException;
     6 import javax.servlet.annotation.WebServlet;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 /**  
    12  * ClassName:XbqServlet 
    13  * 通过  @WebServlet 注解 整合Servlet
    14  * Date:     2017年11月6日 下午5:13:10
    15  * @author   Joe  
    16  * @version    
    17  * @since    JDK 1.8
    18  */
    19 @WebServlet(urlPatterns = "/joe/*")
    20 public class JoeServlet extends HttpServlet{
    21 
    22     private static final long serialVersionUID = 1L;
    23 
    24     @Override
    25     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    26         this.doPost(req, resp);
    27     }
    28 
    29     @Override
    30     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    31         resp.setCharacterEncoding("UTF-8");
    32         resp.setContentType("text/html");  
    33         PrintWriter out = resp.getWriter();  
    34         out.println("<html>");  
    35         out.println("<head>");  
    36         out.println("<title>Hello World</title>");  
    37         out.println("</head>");  
    38         out.println("<body><center>");  
    39         out.println("<h3>我是通过   @WebServlet 注解注册Servlet的</h3>");  
    40         out.println("</center></body>");  
    41         out.println("</html>"); 
    42     }
    43 }

      2) Filter

     1 package com.xsjt.filter;
     2 
     3 import java.io.IOException;
     4 import javax.servlet.Filter;
     5 import javax.servlet.FilterChain;
     6 import javax.servlet.FilterConfig;
     7 import javax.servlet.ServletException;
     8 import javax.servlet.ServletRequest;
     9 import javax.servlet.ServletResponse;
    10 import javax.servlet.annotation.WebFilter;
    11 import javax.servlet.http.HttpServletRequest;
    12 import org.slf4j.Logger;
    13 import org.slf4j.LoggerFactory;
    14 import org.springframework.core.annotation.Order;
    15 
    16 /**  
    17  * ClassName:JoeFilter 
    18  * 自定义  Filter
    19  *         @Order注解表示执行过滤顺序,值越小,越先执行
    20  * Date:     2017年11月6日 下午6:01:33
    21  * @author   Joe  
    22  * @version    
    23  * @since    JDK 1.8
    24  */
    25 @Order(1)
    26 @WebFilter(filterName = "joeFilter", urlPatterns = "/*")
    27 public class JoeFilter implements Filter {
    28     
    29     private static Logger logger = LoggerFactory.getLogger(JoeFilter.class);
    30 
    31     @Override
    32     public void init(FilterConfig filterConfig) throws ServletException {
    33         logger.info("--joe--初始化JoeFilter!");
    34     }
    35 
    36     @Override
    37     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    38         HttpServletRequest req = (HttpServletRequest)request;
    39         logger.info(req.getRequestURL() + "---joe---> doFilter");
    40         chain.doFilter(request, response);
    41     }
    42 
    43     @Override
    44     public void destroy() {
    45         logger.info("--joe--销毁JoeFilter!");
    46     }
    47 }

      3) Listener

     1 package com.xsjt.listener;
     2 
     3 import javax.servlet.ServletContextEvent;
     4 import javax.servlet.ServletContextListener;
     5 import javax.servlet.annotation.WebListener;
     6 import org.slf4j.Logger;
     7 import org.slf4j.LoggerFactory;
     8 
     9 /**  
    10  * ClassName:JoeListener 
    11  * Date:     2017年11月6日 下午6:28:29
    12  * @author   Joe  
    13  * @version    
    14  * @since    JDK 1.8
    15  */
    16 @WebListener
    17 public class JoeListener implements ServletContextListener{
    18     
    19     private static Logger logger = LoggerFactory.getLogger(JoeListener.class);
    20 
    21     @Override
    22     public void contextInitialized(ServletContextEvent sce) {
    23         logger.info("--Joe-监听器-ServletContext 初始化");
    24         logger.info(sce.getServletContext().getServerInfo());
    25     }
    26 
    27     @Override
    28     public void contextDestroyed(ServletContextEvent sce) {
    29         logger.info("--Joe-监听器-ServletContext 销毁");
    30     }
    31 }

    3.源码下载

      https://gitee.com/xbq168/spring-boot-learn

  • 相关阅读:
    pytest+allure生成测试报告
    pytest之fixture使用详解
    pytest框架介绍
    使用records库操作SQL并且查询MySQL数据库
    python模块之codecs
    项目总结
    第二阶段团队绩效评分
    软件发布2.0
    “随手记”开发记录day20
    “随手记”开发记录day19
  • 原文地址:https://www.cnblogs.com/xbq8080/p/7768916.html
Copyright © 2020-2023  润新知