How to respond with HTTP status code in a Spring MVC @RestController @ResponseBody class returning an object?

后端 未结 2 1680
萌比男神i
萌比男神i 2020-12-23 11:57

I\'m trying to have a @RestController which takes a @PathVariable return a specific object in JSON format, along with proper status code. So far th

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 12:31

    A @RestController is not appropriate for this. If you need to return different types of responses, use a ResponseEntity where you can explicitly set the status code.

    The body of the ResponseEntity will be handled the same way as the return value of any @ResponseBody annotated method.

    @RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET)
    public ResponseEntity fetchWellData(@PathVariable String apiValue){
        try{
            OngardWell ongardWell = new OngardWell();
            ongardWell = ongardWellService.fetchOneByApi(apiValue);
    
            return new ResponseEntity<>(ongardWell, HttpStatus.OK);
        }catch(Exception ex){
            String errorMessage;
            errorMessage = ex + " <== error";
            return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
        }
    }
    

    Note that you don't need @ResponseBody on a @RequestMapping method within a @RestController annotated class.

提交回复
热议问题