Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple response http status in Spring MVC

Having the following code:

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

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

like image 374
Ali Avatar asked Sep 19 '11 17:09

Ali


People also ask

How do I return 204 status in Spring boot?

You can use the @ResponseStatus annotation. This way you can have a void method and you don't have to build a ResponseEntity. BTW returning 200 when the object exists and 204 otherwise it's a bit unusual regarding API REST design. It's common to return a 404 (not found) when the requested object is not found.

How do I set a response status code in Spring?

Sending Specific Response Status Codes The very basic way of sending response status is to use ResponseEntity object, which is returned by a controller. Controller can set a specific response status in the Response. Alternatively, we can use @ResponseStatus annotation to specify the desired status code.


1 Answers

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

like image 124
Slava Semushin Avatar answered Oct 15 '22 01:10

Slava Semushin