Search code examples
springforwarding

Spring ResponseEntity and forward


Im a SpringBoot application have a REST controller that handles several cases and one of these cases it must forward to another controller.

@PutMapping(
        value = "/rest/endpoint",
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<CustomObject> doPut(@RequestBody myDataToBeHandled) {

   if(caseAHolds(myDataToBeHandled){
      return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
   }
   else if(caseBHolds(myDataToBeHandled){
      return new ResponseEntity<>(null, HttpStatus.OK);
   }
   else if(caseCHolds(myDataToBeHandled){
     // Redirect here
   }

}

I have seen an example on how to do this for a redirect?


Solution

  • You need to set the Location header as shown below in order to redirect the request to another URL as shown below:

    @PutMapping(
            value = "/rest/endpoint",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<CustomObject> doPut(@RequestBody myDataToBeHandled) {
    
       if(caseAHolds(myDataToBeHandled){
          return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
       }
       else if(caseBHolds(myDataToBeHandled){
          return new ResponseEntity<>(null, HttpStatus.OK);
       }
       else if(caseCHolds(myDataToBeHandled){
         // Redirect here
         HttpHeaders headers = new HttpHeaders();
         headers.add("Location", "ADD_URL_HERE");
         return new ResponseEntity<CustomObject>(headers, HttpStatus. OK);
       }
    }