Saveendra Ekanayake Saveendra Ekanayake - 1 year ago 115
Java Question

How to return different types of ResponseEntity in Spring MVC

I have written simple rest application using Spring MVC 4. Within the controller I have return

. But in some cases I want to give success JSON and if there is validation error I want to give error JSON. Currently success and error responses are totally different, So I have created 2 classes for error and success. Within the controller I want to return
, if the internal logic is okay. Otherwise I want to return
. Is there any way to do it.

are the 2 classes that i use to represent success and error response.

Answer Source

Its possible to return ResponseEntity without using generics, such as follows,

public ResponseEntity method() {
    boolean isValid = // some logic
    if (isValid){
        return new ResponseEntity(new Success(), HttpStatus.OK);
        return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST);