具有以下代码:
@RequestMapping(value = "/system/login",method = RequestMethod.GET) public void login(@RequestBody Login login) { if(login.username == "test" && login.password == "test") { //return HTTP 200 } else { //return HTTP 400 } }
我想根据我的逻辑返回两种不同的HTTP状态.实现这一目标的最好方法是什么?
解决方法
有人在SO中提出的一种方法是抛出不同的异常,这些异常将被不同的异常处理程序所捕获:
@RequestMapping(value = "/system/login",method = RequestMethod.GET) public void login(@RequestBody Login login) { if(login.username == "test" && login.password == "test") { throw new AllRightException(); } else { throw new AccessDeniedException(); } } @ExceptionHandler(AllRightException.class) @ResponseStatus(HttpStatus.OK) public void whenAllRight() { } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void whenAccessDenied() { }
也可以看看:
> @ExceptionHandler
> @ResponseStatus
BTW,你的示例代码包含错误:login.password ==“test”你应该使用equals()有:)
更新:我发现另一种方法更好,因为它不使用例外:
@RequestMapping(value = "/system/login",method = RequestMethod.GET) public ResponseEntity<String> login(@RequestBody Login login) { if(login.username == "test" && login.password == "test") { return new ResponseEntity<String>("OK" HttpStatus.OK); } return new ResponseEntity<String>("ERROR",HttpStatus.BAD_REQUEST); }