Spring Boot之 Servlet、Fiter、Listener的使用

Servlet的使用

  • 新建MyServlet类

package com.adagio.chat.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

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(
        name = "myservlet",
        urlPatterns = {"/myservlet1", "/myservlet2"}
)
public class MyServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        
        Writer writer = response.getWriter();
        writer.write("<html><body>Hello World</body></html>");
    }
}

Filter的使用

  • 使用方式和Servlet十分类似

package com.adagio.chat.servlet;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

//@WebFilter(servletNames = "myservlet")
@WebFilter(urlPatterns = "/myservlet1")
public class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        ServletContext servletContext = getServletContext();
        servletContext.log("url myservlet was filter");
        
        filterChain.doFilter(request, response);
    }

}

Listener的使用

  • 使用方式也是类似的

package com.adagio.chat.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

@WebListener
public class MyListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        
        ServletContext servletContext = request.getServletContext();
        servletContext.log("request was destroyed");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        
        ServletContext servletContext = request.getServletContext();
        servletContext.log("request was initialized");
    }

}

执行顺序

2017-09-10 16:11:18.247  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : request was initialized
2017-09-10 16:11:18.271  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : url myservlet was filter
2017-09-10 16:11:18.271  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : servlet was doGet
2017-09-10 16:11:18.275  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : request was destroyed
  • 先监听器的初始化,再经过滤器,然后执行doGet方法,最后执行监听器的消亡

使用注入的方式注册

  • 效果和上面的方式一样的,具体实现见代码

package com.adagio.chat.spring.boot;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

public class MyFilter2 extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//        ServletContext servletContext = getServletContext();
//        
//        //动态获取URI
//        String requestURI = request.getRequestURI();
//        
//        servletContext.log("url "+requestURI+" was filter from MyFilter2");
        
        doSomething();
        filterChain.doFilter(request, response);
    }
    
    /**
     * 当没有request的时候,可以使用这种方式获取request
     */
    public void doSomething(){
        
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
        
        HttpServletRequest request = servletRequestAttributes.getRequest();
        ServletContext servletContext = getServletContext();
        
        //动态获取URI
        String requestURI = request.getRequestURI();
        
        servletContext.log("url "+requestURI+" was filter from MyFilter2");
        
    }

}
package com.adagio.chat.spring.boot;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

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


public class MyServlet2 extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        
        ServletContext servletContext = request.getServletContext();
        servletContext.log("servlet2 was doGet");
        
        Writer writer = response.getWriter();
        writer.write("<html><body>Hello World From MyServlet2</body></html>");
    }
}
package com.adagio.chat;

import javax.servlet.DispatcherType;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.adagio.chat.servlet.MyListener;
import com.adagio.chat.spring.boot.MyFilter2;
import com.adagio.chat.spring.boot.MyServlet2;

@SpringBootApplication
@ServletComponentScan(basePackages = {"com.adagio.chat.servlet"})
public class ChatApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChatApplication.class, args);
    }
    
    @Bean
    public static ServletRegistrationBean servletRegistrationBean(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        
        servletRegistrationBean.setServlet(new MyServlet2());
        servletRegistrationBean.addUrlMappings("/spring/boot/myservelt2");
        servletRegistrationBean.setName("myservlet2");
        
        return servletRegistrationBean;
    }
    
    @Bean
    public static FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        
        filterRegistrationBean.setFilter(new MyFilter2());
//        filterRegistrationBean.addUrlPatterns("/spring/boot/myservelt2");
        filterRegistrationBean.addServletNames("myservlet2");
        filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
        
        return filterRegistrationBean;
    }
    
    /**
     * 监听器会监听所有请求
     * 可以重复注册监听器
     * @return
     */
    @Bean
    public static ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean(){
        ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return servletListenerRegistrationBean;
    }
    
}

急事慢做:成长是长时间努力、积累和进步的结果,是水到渠成的事情,绝不是心急就能做到的。
生长速度越快的树木,其致密度就越低,生命往往也越短暂;而松树、柏树、胡杨等树种,要上百年才能成材,用起来却可千年不朽。 - 俞敏洪


麦冬
315 声望13 粉丝

越成熟的稻穗,越饱满厚实