1. 程式人生 > >05-SpringBoot之WEB(三)—— ——整合Interceptor

05-SpringBoot之WEB(三)—— ——整合Interceptor

SpringBoot之WEB(三)

Interceptor

1 自定義Interceptor

使用 @Component 讓 Spring 管理其生命週期:

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import
org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by HuangJun * 10:43 2018/11/9 */ @Component public class MyInterceptor implements HandlerInterceptor
{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("========preHandle========="); System.out.println(((HandlerMethod)handler).getBean().getClass().getName()); System.out.
println(((HandlerMethod)handler).getMethod().getName()); request.setAttribute("startTime", System.currentTimeMillis()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("========postHandle========="); Long start = (Long) request.getAttribute("startTime"); System.out.println("耗時:"+(System.currentTimeMillis() - start)); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { System.out.println("========afterCompletion========="); Long start = (Long) request.getAttribute("startTime"); System.out.println("耗時:"+(System.currentTimeMillis() - start)); System.out.println(exception); } }

2 註冊Interceptor

在上文建立的 InterceptorConfig類:

import com.springboot.web.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by HuangJun
 * 10:50 2018/11/9
 */
@Configuration
public class InterceptorConfig  extends WebMvcConfigurerAdapter {
    @Autowired
    private MyInterceptor myInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor);
    }
}

3 執行結果

觀察控制檯列印輸出,結果如下圖
在這裡插入圖片描述

4 原始碼下載

原始碼下載地址https://download.csdn.net/download/huangjun0210/10774393