开发者

Multiple response http status in Spring MVC

Having the following code:

@Reque开发者_JAVA技巧stMapping(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
    }
}

I would like to return two different HTTP statuses based on my logic. What is the best way to achieve this?


One approach which someone suggested at SO is to throw different exceptions which will be catch by different exception handlers:

@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() {

}

See also:

  • @ExceptionHandler
  • @ResponseStatus

BTW, your example code contains error: login.password == "test" you should use equals() there :)


Updated: I found another approach which even better because it doesn't use exceptions:

@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);
}

See also ResponseEntity API

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜