Spring Boot - Servlet, Filter, Monitor, Interceptor

Keywords: Java Spring JSON JSP

Spring Boot - Servlet, Filter, Monitor, Interceptor

In the last article, we explained how to configure and integrate spring boot (json,jsp,freemarker). What is unclear is that Click to understand

Two Implementations of Servlet

  • Manual injection via @Bean
    Implement a method to return the Servlet Registration Bean and register the object in spring. This code needs to be placed in the spring boot automatically scanned directory. It is recommended that it be placed in the @Configuration identifier class for unified management.

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new HelloServlet(),"/xiaohong");
    }
  • Automatic injection via @WebServlet

    • Add the annotation @ServletComponentScan to turn on servlet scanning

    • Add the annotation @WebServlet, identify the class as a servlet, and declare urlPath

@ServletComponentScan
@SpringBootApplication
public class Start {......}        
@WebServlet("/xiaohong")
public class HelloServlet extends HttpServlet {......}
  • Example: HelloServlet.java

package com.wanye.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;
import java.io.PrintWriter;

/**
 * Created by wanye on 2017/5/24.
 */
@WebServlet("/xiaohong")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>do get<<");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>do post<<");
        PrintWriter out = resp.getWriter();
        out.print("hello @xiaohong");
        out.close();
    }
}

Filter Filter and Listener

Filter Filter and Listener are implemented in the same way as Servlet. Here are the differences. You can try it yourself.

  1. Manual injection via @Bean

    1. Filter needs to implement the method of returning FilterRegistrationBean

    2. Listener needs to implement the method of returning ServletListener Registration Bean

  2. Automatic injection through annotations

    1. Filter needs to be annotated @WebFilter to identify this class as Filter

    2. Listener needs to add the annotation @WebListener to identify the class as Listener

Interceptor

Servlets, filters, listeners are explained above. Careful students can find that they belong to the Api provided by javax.servlet.

Interceptor Principle

Simply speaking, it is realized by dynamic proxy, and the accessed target method is executed by proxy class (method), so that we can do some processing before and after the execution of the method we really want to execute, and the code can be more abstract by interceptor. For more information about interceptors and dynamic agents, please refer to the information.

HTTP Interceptor

Implementing Http Interceptor in Spring

  1. Create the interceptor class and implement the Handler Interceptor interface. perHandler returns true to indicate that by intercepting

package com.wanye.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wanye on 2017/5/24.
 */
public class HelloInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(">>interceptor preHandle<<");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(">>interceptor postHandle Call after request processing, but before view is rendered( Controller After method invocation)<<");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(">>interceptor afterCompletion<<");
    }
}
  1. Create a Java class that inherits WebMvcConfigurerAdapter and overrides the addInterceptors method, @Configuration

package com.wanye.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by wanye on 2017/5/24.
 */
@Configuration
public class HelloConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HelloInterceptor()).addPathPatterns("/**");

    }
}
  1. Instantiate the interceptor, and then manually add the object to the interceptor chain (in the addInterceptors method)

summary

This article explains the two ways of registering Servlet/Filter/Listener (the concept of Servlet/Filter/Listener is known by you), and the basic principle of the interceptor, and implements the HTTP interceptor through annotations. In addition, this article also has a question: Why can't the Http interceptor implemented in Spring intercept our customized servlet request? Welcome to leave a message for discussion.

Annotation Meaning
  1. @ Bean // @Bean clearly indicates the way to produce a bean and gives it to Spring container management

  2. @ Servlet ComponentScan // When scanning Servlet components with @Servlet ComponentScan, Servlet, filter and listener can be automatically registered through @WebServlet, @WebFilter and @WebListener

  3. @ WebServlet("/hello")@WebFilter@WebListener// Individual Identification

Last

If this article is helpful to you, I would like to commend it.

Posted by printf on Sun, 23 Jun 2019 13:16:57 -0700