- 注解类(Authorized.java)
@documented @Inherited @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Authorized { }
- 拦截器处理类(AuthInterceptor.java)
public class AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { HandlerMethod handlerMethod = (HandlerMethod) handler; Authorized authorized = handlerMethod.getMethodAnnotation(Authorized.class); if (authorized == null) { authorized = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Authorized.class); } if (authorized != null) { return isAuthorized(request, response); } return true; } private boolean isAuthorized(HttpServletRequest request, HttpServletResponse response) { //CURRENT_USER已经在登录完成的时候存到session中了 JSONObject userJSON = (JSONObject) request.getSession().getAttribute("CURRENT_USER"); if (userJSON != null) { return true; } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8;"); try (PrintWriter writer = response.getWriter()) { String buffer = JSONObject.toJSONString( BeeResponseEntity.failed(ErrorCode.UNAUTHORIZED), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat ); writer.print(buffer); return false; } catch (IOException e) { return false; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)