過濾器Filter,是Servlet的一種技術。可經過Filter,對請求進行攔截,好比判斷用戶是否登陸、驗證黑名單等而且可對請求進行預處理。java
接下來介紹使用WebFilter配置過濾器並實現讀取cookie判斷用戶是否登錄json
編寫Filter類cookie
/註冊器名稱爲customFilter,攔截的url爲全部 @WebFilter(filterName = "customFilter",urlPatterns = ["/*"]) class CustomFilter:Filter { var logger = LoggerFactory.getLogger(this::class.java)!! override fun destroy() { logger.info("CustomFilter destroy") } override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) { 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 } } logger.info("CustomFilter start") chain?.doFilter(request,response) logger.info("CustomFilter complete") } override fun init(filterConfig: FilterConfig?) { logger.info("CustomFilter init") } }
而後在啓動類加入@ServletComponentScan註解,確保能夠掃描到CustomFilterapp
@SpringBootApplication @ServletComponentScan class Demo1Application fun main(args: Array<String>) { runApplication<Demo1Application>(*args) }
隨便請求一下,發現返回,咱們的過濾器生效了ide
HTTP/1.1 200 Content-Type: */*;charset=ISO-8859-1 Content-Length: 15 Date: Thu, 18 Oct 2018 07:23:58 GMT No Access Token
那麼試一下接受json格式,添加請求頭this
Accept: application/json
返回了咱們想要的jsonurl
HTTP/1.1 200 Content-Type: application/json;charset=ISO-8859-1 Content-Length: 52 Date: Thu, 18 Oct 2018 07:27:08 GMT {"data":null,"succes":false,"msg":"No Access Token"}
若是加上Cookie(以下),那麼就能夠正常經過咱們的過濾器了code
Cookie: userid=3;