问题
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?
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/43033790/spring-responseentity-and-forward