SpringBoot入門(14)- SpringBoot 中使用攔截器
阿新 • • 發佈:2018-12-13
1、實現攔截器介面HandlerInterceptor
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; public class LogHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("=====preHandle=========="+handler.getClass()); return true; } }
2、新類繼承WebMvcConfigurerAdapter,註冊攔截器
import org.springframework.boot.SpringBootConfiguration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.zemel.test.rest.LogHandlerInterceptor; @SpringBootConfiguration public class WebConfig extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LogHandlerInterceptor()); } }