java没有spring之前_java – 有没有办法在使用spring执行rest api之前验证令牌

你可以使用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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值