你可以使用HandlerInterceptor来处理你的令牌.
HandlerInterceptor.preHandle(HttpServletRequest请求,HttpServletResponse响应,对象处理程序)将在任何RequestMapping之前执行.
验证你在preHandle.if令牌中的令牌是有效的继续,否则抛出异常,控制器建议将处理其余的.
暴露MappedInterceptor的bean类,spring将自动加载HandlerInterceptor bean包含.
ControllerAdvice和ExceptionHandler可以捕获异常并返回错误消息
完整的例子
@RestController
@EnableAutoConfiguration
public class App {
@RequestMapping("/")
public String index() {
return "hello world";
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public static class MyException extends RuntimeException {
}
@Bean
@Autowired
public MappedInterceptor getMappedInterceptor(MyHandlerInterceptor myHandlerInterceptor) {
return new MappedInterceptor(new String[] { "/" }, myHandlerInterceptor);
}
@Component
public static class TestBean {
public boolean judgeToken(HttpServletRequest request) {
String token = request.getParameter("token");
if (token == null) {
throw new MyException();
}
return true;
}
}
@Component
public static class MyHandlerInterceptor implements HandlerInterceptor {
@Autowired
TestBean testBean;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return testBean.judgeToken(request);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
}
}
@ControllerAdvice
public static class MyExceptionHandler {
@ExceptionHandler(MyException.class)
@ResponseBody
public Map handelr() {
Map m1 = new HashMap();
m1.put("status", "error");
m1.put("message", "Sorry, your provided token information expired or not exists.");
return m1;
}
}
}