Spring ResponseEntity and forward

为君一笑 提交于 2021-02-08 07:40:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!