在spring boot1.x中,使用攔截器,通常進行以下配置:java
@Configuration public class AppConfig extends WebMvcConfigurerAdapter { @Resource private FRInterceptor fRInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //自定義攔截器,添加攔截路徑和排除攔截路徑 registry.addInterceptor(fRInterceptor).addPathPatterns("api/**").excludePathPatterns("api/login"); } }
可是在spring boot2.x中,WebMvcConfigurerAdapter被deprecated,雖然繼承WebMvcConfigurerAdapter這個類雖然有此便利,但在Spring5.0裏面已經deprecated了。web
官方文檔也說了,WebMvcConfigurer接口如今已經有了默認的空白方法,因此在Springboot2.0(Spring5.0)下更好的作法仍是implements WebMvcConfigurer。spring
import javax.annotation.Resource; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.spring.pro.interceptor.FileUploadInterceptor; /** * @ClassName: WebConfig * @Description: * @author weiyb * @date 2018年5月7日 上午11:30:58 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Resource private FileUploadInterceptor fileUploadInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // 自定義攔截器,添加攔截路徑和排除攔截路徑 registry.addInterceptor(fileUploadInterceptor).addPathPatterns("/**"); } }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 文件上傳攔截器 * @ClassName: FileUploadInterceptor * @Description: * @author weiyb * @date 2018年5月7日 上午11:51:53 */ @Component public class FileUploadInterceptor implements HandlerInterceptor { /* * 視圖渲染以後的操做 */ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } /* * 處理請求完成後視圖渲染以前的處理操做 */ @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } /* * 進入controller層以前攔截請求 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { System.out.println("getContextPath:" + request.getContextPath()); System.out.println("getServletPath:" + request.getServletPath()); System.out.println("getRequestURI:" + request.getRequestURI()); System.out.println("getRequestURL:" + request.getRequestURL()); System.out.println("getRealPath:" + request.getSession().getServletContext().getRealPath("image")); return true; } }