Be serious about writing, not clickbait.

The article is available at Github.com/niumoo/Java… And program ape Alang’s blog, point attention, don’t get lost.

1. The interceptor

The Interceptor Interceptor in Springboot is also the Interceptor in MVC, leaving out the XML configuration. There is no essential difference, it is implemented by implementing several methods in the HandlerInterceptor. The functions of several methods are as follows.

  1. PreHandle is executed before entering the Habdler method and is used for identity authentication and authorization.
  2. PostHandle is executed after entering the Handler method and before returning to modelAndView. It is usually used for stuffing common model data, etc.
  3. AfterCompletion is the final processing, which is generally used for log collection and unified follow-up processing.

1.1 Importing Dependencies

 <! -- Spring Boot Web Development integration -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-json</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <! -- Ali Fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <! -- Lombok tools -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <! The springBoot file handler will be displayed when the springboot file is configured.
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <! -- Unit tests -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

Copy the code

1.2 Writing interceptors

package net.codingme.boot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/** * <p> * Interceptor **@Author niujinpeng
 * @Date2019/1/6 16:54 * /
@Slf4j
public class LogHandlerInterceptor implements HandlerInterceptor {

    /** * returns true before the method is executed through **@param request
     * @param response
     * @param handler
     * @return* /
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        StringBuffer requestURL = request.getRequestURL();
        log.info("PreHandle request URL:" + requestURL.toString());
        return true;
    }

    /** * execute * before returning to modelAndView@param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        log.info("PostHandle before returning to modelAndView");
    }

    /** * Execute Handler to finish executing this method *@param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("AfterCompletion, after the requested method has been fully returned."); }}Copy the code

1.3 Configuring interceptors

After omitting the interceptor configuration part of the XML, configure the custom interceptor in the manner recommended by SpringBoot.

package net.codingme.boot.config;


import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/** * <p> * 1. Use FastJSON * 2. Configure time formatting * 3. 4. Add custom interceptor * *@Author niujinpeng
 * @Date2018/12/13 and * /
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /** * Custom JSON converter **@param converters
     */
    @Override
    public void configureMessageConverters(List
       
        > converters)
       > {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // Format the date
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        // Handle Chinese garbled characters
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);

        converter.setSupportedMediaTypes(fastMediaTypes);
        converter.setFastJsonConfig(fastJsonConfig);
        converters.add(converter);
    }

    /** * Add custom interceptor *.addPathPatterns("/**") intercepts request paths *.excludePathPatterns("/user"); Excluded request path * *@param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogHandlerInterceptor())
                .addPathPatterns("/ * *")
                .excludePathPatterns("/user"); }}Copy the code

Section programming

  1. AOP: Faceted (aspect) oriented programming, extending functionality without modifying source code implementation
  2. AOP adopts horizontal extraction mechanism instead of repeating code in traditional vertical inheritance system
  3. AOP’s underlying implementation uses dynamic proxies
    • Use dynamic proxies to create interface implementation class proxy objects
    • Use dynamic proxies to create subclass proxy objects for classes without interfaces
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/** * <p> * Use AOP to log access * use@BeforeEnter content * use at the beginning of the pointcut@AfterEnter content * at the end of the pointcut@AfterReturningThe pointcut returns the content after the pointcut returns the content (which can be used to do some processing on the processing return value) *@AroundCut content before and after a pointcut, and control when the pointcut's own content * uses are performed@AfterThrowingNote: * Aspect:AOP * Component: Bean * Slf4j: Can output logs directly using log * Order: Multiple AOP cut the same method when the priority, the smaller the higher the priority. * Operations before the pointcut are executed in ascending order * * Operations after the pointcut are executed in ascending order * *@Author niujinpeng
 * @Date2019/1/4 "* /

@Aspect
@Component
@Slf4j
@Order(1)
public class LogAspect {
    /** * Threads store information */
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /** * Defines pointcut * first * : identifies all return types * letter path: package path * two dots.. : current package and subpackages * second * : all classes * third * : all methods * Last two points: all types of arguments */
    @Pointcut("execution(public * net.codingme.boot.controller.. *. * (..) )"
    public void webLog(a) {}/** * Enter the content ** at the beginning of the pointcut@param joinPoint
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // Record the request time
        startTime.set(System.currentTimeMillis());
        // Get the request field
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // Record the request
        log.info("Aspect-URL: " + request.getRequestURI().toLowerCase());
        log.info("Aspect-HTTP_METHOD: " + request.getMethod());
        log.info("Aspect-IP: " + request.getRemoteAddr());
        log.info("Aspect-REQUEST_METHOD: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("Aspect-Args: " + Arrays.toString(joinPoint.getArgs()));
    }

    /** * Process content after the pointcut */
    @After("webLog()")
    public void doAfter(a) {}/** * Enter the content after the pointcut return content (which can be used to do some processing on the processing return value) */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        log.info("Aspect-Response: " + ret);
        Long endTime = System.currentTimeMillis();
        log.info("Aspect-SpeedTime: " + (endTime - startTime.get()) + "ms"); }}Copy the code

Access to view interceptor and AOP log output.

09:57:15. 2836-408 the INFO [nio - 8080 - exec - 1] N.C.B oot. The config. LogHandlerInterceptor: PreHandle request URL: http://localhost:8080/ 09:57:15. 2836-413 the INFO [nio - 8080 - exec - 1] net. Codingme. Boot. Config. LogAspect: Aspect - URL: / 09:57:15. 413 INFO - 2836 [nio - 8080 - exec - 1] net. Codingme. Boot. Config. LogAspect: Aspect - HTTP_METHOD: The GET 09:57:15. 2836-413 the INFO [nio - 8080 - exec - 1] net. Codingme. Boot. Config. LogAspect: Aspect - IP: 0:0:0:0:0:0:1-0 09:57:15. 414 INFO - 2836 [nio - 8080 - exec - 1] net. Codingme. Boot. Config. LogAspect: Aspect-REQUEST_METHOD: Net. Codingme. Boot. Controller. HelloController. Index 09:57:15. 2836-415 the INFO [nio - 8080 - exec - 1) net.codingme.boot.config.LogAspect : Aspect-Args: [] 09:57:15. 2836-424 the INFO [nio - 8080 - exec - 1] net. Codingme. Boot. Config. LogAspect: Aspect - the Response: Greetings from Spring Boot! SpringBoot is a spring application 09:57:15. 425 INFO - 2836 [nio - 8080 - exec - 1] net. Codingme. Boot. Config. LogAspect: Aspect - SpeedTime: 12 ms 09:57:15. 2836-436 the INFO [nio - 8080 - exec - 1] N.C.B oot. The config. LogHandlerInterceptor: PostHandle before returning to modelAndView 09:57:15. 437 INFO - 2836 [nio - 8080 - exec - 1] N.C.B oot. The config. LogHandlerInterceptor: AfterCompletion executes after the requested method has fully returnedCopy the code

3. Servlet,Filter,Listener

Servlet, Filter, Listener are the core content of Java Web, so how to use in Springboot?

3.1 write a Servlet

package net.codingme.boot.servlet;

import lombok.extern.slf4j.Slf4j;

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;

/**
 * <p>
 * @WebServlet(urlPatterns = "/ myServlet ") // Define access paths *@Author niujinpeng
 * @Date2019/1/24 25 * /
@Slf4j
@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    public void init(a) throws ServletException {
        log.info("Servlet initialization begins");
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("Servlet starts processing GET methods");
        PrintWriter writer = resp.getWriter();
        writer.println("Hello Servlet");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    public void destroy(a) {
        log.info("Servlet begins to destroy");
        super.destroy(); }}Copy the code

3.2 write Filter

package net.codingme.boot.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * <p>
 *
 * @Author niujinpeng
 * @Date2019/1/24 now * /
@Slf4j
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        log.info("Interceptor intercepts."); filterChain.doFilter(request, response); }}Copy the code

3.3 write the Listener

package net.codingme.boot.listener;

import lombok.extern.slf4j.Slf4j;

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

/**
 * <p>
 *
 * @Author niujinpeng
 * @Date2019/1/24 * / art
@Slf4j
@WebListener
public class MyListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("Listener initialization started");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("Listener destruction begins."); }}Copy the code

3.4 Adding to a Container

There are two ways to add to a container, the first using an annotation scan.

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

/ * * *@ServletComponentScanScan Servlet,Filter,Listener to add to container */
@SpringBootApplication
@ServletComponentScan
public class BootApplication {

    public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); }}Copy the code

Or use configuration classes to add to the container.

/** * <p> * Register the Servlet Filter Listener here or use it@ServletComponentScan
 *
 * @Author niujinpeng
 * @Date2019/1/24 ticket * /
@Configuration
public class WebCoreConfig {

    @Bean
    public ServletRegistrationBean myServlet(a) {
        return new ServletRegistrationBean<>(new MyServlet());
    }

    @Bean
    public FilterRegistrationBean myFitler(a) {
        return new FilterRegistrationBean<>(new MyFilter());
    }

    @Bean
    public ServletListenerRegistrationBean myListener(a) {
        return new ServletListenerRegistrationBean(newMyListener()); }}Copy the code

Start you can see the listener start in the console.

11:35:03. 8616-744 the INFO [main] O.S.W eb. Context. ContextLoader: Root WebApplicationContext: Initialization completed in 1364 ms 11:35:03. 798 INFO - 8616 net. [the main] codingme. Boot. Listener. MyListener: Listeners to initialize 11:35:03. 8616-892 the INFO [main] O.S.S.C oncurrent. ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor' 11:35:04.055 INFO 8616 -- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''Copy the code

Access the Servlet to see the interceptor and Servlet in effect.

11:36:55. 3760-552 the INFO [nio - 8080 - exec - 1] net. Codingme. Boot.. Servlet MyServlet: Servlet to initialize 11:36:55. 556 INFO - 3760 [nio - 8080 - exec - 1] net. Codingme. Boot. Filter. MyFilter: Interceptors to intercept 11:36:55. 556 INFO - 3760 [nio - 8080 - exec - 1] net. Codingme. Boot.. Servlet MyServlet: servlet began to deal with the GET methodCopy the code

The article code has been uploaded to GitHub Spring Boot Web Development – Intercept processing. The article code has been uploaded to GitHub Spring Boot Web development – Servlet,Filter,Listener.

After < >

Hello world 🙂 I am program ape alang, conscientiously write articles, do not do clickbait. If you like this article, you can follow the public account “Programape Alang”, or programape Alang’s blog. Thanks for your support ❤.

This article has also been compiled at GitHub.com/niumoo/Java… Welcome Star.