如何在返回对象的Spring MVC@RestController @ResponseBody类中使用HTTP状态代码进行响应?

2022-09-01 10:09:01

我正在尝试让一个哪个以JSON格式返回特定对象,以及正确的状态代码。到目前为止,代码的方式是,它将以JSON格式返回对象,因为它默认使用Jackson库中构建的Spring 4。@RestController@PathVariable

但是,我不知道如何做到这一点,因此它会向用户发送一条消息,说我们想要一个api变量,然后是JSON数据,然后是错误代码(或成功代码,具体取决于一切顺利)。示例输出为:

请输入 api 值作为参数(注意,如果需要,也可以采用 JSON 格式)

{“id”: 2, “api”: “3000105000” ... }(注意这将是 JSON 响应对象)

状态代码 400(或正确的状态代码)


带有参数的 url 如下所示

http://localhost:8080/gotech/api/v1/api/3000105000

到目前为止,我拥有的代码:

@RestController
@RequestMapping(value = "/api/v1")
public class ClientFetchWellDataController {

    @Autowired
    private OngardWellService ongardWellService;

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

答案 1

A 不适合于此。如果需要返回不同类型的响应,请使用可以显式设置状态代码的 。@RestControllerResponseEntity<?>

的处理方式与任何带注释方法的返回值相同。bodyResponseEntity@ResponseBody

@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);
    }
}

请注意,您不需要带批注的类中的方法。@ResponseBody@RequestMapping@RestController


答案 2

惯用的方法是使用异常处理程序,而不是在常规请求处理方法中捕获异常。异常的类型决定了响应代码。(403 表示安全错误,500 表示意外平台异常,无论您喜欢什么)

@ExceptionHandler(MyApplicationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleAppException(MyApplicationException ex) {
  return ex.getMessage();
}

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAppException(Exception ex) {
  return ex.getMessage();
}