赞
踩
在写项目过程中,使用springsecurity进行权限管理,并自定义token过滤器加到验证过滤器之前,这时就会出现一个问题,当token过期时,会调用springsecurity的异常处理机制,而不会使用我的全局异常处理
自定义过滤器
package com.fruiter.filter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.ExpiredJwtException; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 处理Controller抛出异常会被该过滤器处理 */ public class ControllerExceptionFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { filterChain.doFilter(request, response); } catch (ExpiredJwtException e) { e.printStackTrace(); response.setStatus(401); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.getWriter().print("token过期"); } } public String convertObjectToJson(Object object) throws JsonProcessingException { if (object == null) { return null; } ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(object); } }
加入进行管理
//WebAsyncManagerIntegrationFilter是第一个异常处理的过滤器
http.addFilterBefore(new ControllerExceptionFilter(), WebAsyncManagerIntegrationFilter.class);
这里对response
设置其状态码,即response.setStatus(401);
不能设置如10010这样过大的数字,不然在postman测试的时候会出现报错Error: Parse Error: Response overflow
修改为401即可
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。