最近使用shiro作为权限认证框架,每次通过校验token判断用户是否登录,但是发现一个问题, 自定义的JwtFilter无法通过@ControllerAdvice进行异常捕获(还没到controller呢),但是需要返回统一格式数据
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {
/**
* 执行登录认证
*
* @param request
* @param response
* @param mappedValue
* @return
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
try {
log.info("Filter=====isAccessAllowed========");
executeLogin(request, response);
} catch (Exception e) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setCharacterEncoding("utf-8");
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", HttpStatus.HTTP_UNAUTHORIZED);
jsonObject.put("msg", "Token失效 请重新登陆");
jsonObject.put("data","");
PrintWriter outputStream = response.getWriter();
outputStream.write(jsonObject.toJSONString());
outputStream.close();
} catch (IOException ex) {
log.error("错误"+ex);
}
}
return true;
}
}
为了实现返回统一数据就想了如下办法,直接在filter中响应数据到前端
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setCharacterEncoding("utf-8");
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", HttpStatus.HTTP_UNAUTHORIZED);
jsonObject.put("msg", "Token失效 请重新登陆");
jsonObject.put("data","");
PrintWriter outputStream = response.getWriter();
outputStream.write(jsonObject.toJSONString());
outputStream.close();
} catch (IOException ex) {
log.error("错误"+ex);
}
如果有更好的办法再来更新这篇博客