使用Interceptor攔截器java
Filter 是在 Servlet 規範中定義的,是 Servlet 容器支持的。而攔截器是在 Spring容器內的,是Spring框架支持的。Filter在只在 Servlet 先後起做用。Filters 一般將 請求和響應(request/response) 當作黑盒子,Filter一般不考慮servlet 的實現。攔截器可以深刻到方法先後、異常拋出先後等,所以攔截器的使用具備更大的彈性。容許用戶介入請求的生命週期,在請求過程當中獲取信息,Interceptor 一般和請求更加耦合。在Spring構架的程序中,要優先使用攔截器。幾乎全部 Filter 可以作的事情,interceptor 都可以輕鬆的實現。web
下面咱們實現以前用Filter實現的驗證登錄程序spring
import org.slf4j.LoggerFactory import org.springframework.http.MediaType import org.springframework.web.servlet.HandlerInterceptor import org.springframework.web.servlet.ModelAndView import java.lang.Exception import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class CustomInterceptor: HandlerInterceptor{ var logger = LoggerFactory.getLogger(this::class.java)!! //在請求處理以前進行調用 override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean { val httpServletRequest = request as? HttpServletRequest if (httpServletRequest != null && response != null) { //獲取用戶cookie val userCookie = httpServletRequest.cookies?.firstOrNull { it.name?.toLowerCase() == "userid" } //檢查cookie的正確性 val userId = userCookie?.value?.toIntOrNull() ?: 0 if(userId <= 0){ val accept = httpServletRequest.getHeader("Accept") if (accept?.contains("json") == true) { response.contentType = MediaType.APPLICATION_JSON_VALUE val str = ObjectMapperExtension.instance.writeValueAsString(CommonResult(null, false, "No Access Token")) response.writer.print(str) } else { response.contentType = MediaType.ALL_VALUE response.writer.print("No Access Token") } return false } } logger.info("CustomInterceptor") return true } //請求處理以後進行調用,可是在視圖被渲染以前(Controller方法調用以後) override fun postHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any, modelAndView: ModelAndView?) { logger.info("postHandle") } //在整個請求結束以後被調用,也就是在DispatcherServlet 渲染了對應的視圖以後執行(主要是用於進行資源清理工做) override fun afterCompletion(request: HttpServletRequest, response: HttpServletResponse, handler: Any, ex: Exception?) { logger.info("afterCompletion") } }
import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.InterceptorRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class MyWebMvcConfigurerAdapter: WebMvcConfigurer { override fun addInterceptors(registry: InterceptorRegistry) { registry.addInterceptor(CustomInterceptor()) //註冊要攔截的url .addPathPatterns("/*") //排除url .excludePathPatterns("/login") } }