如何在Spring MVC中响应HTTP状态代码@RestController @ResponseBody类返回一个对象?

Cri*_*ris 29 java spring json spring-mvc

我想有一个@RestController,这需要@PathVariable以JSON格式返回一个特定的对象,适当的状态代码一起.到目前为止,代码的方式是,它将以JSON格式返回对象,因为默认情况下它使用的是Spring库中内置的Spring 4.

但是我不知道怎么做它所以它会给用户一个消息,说我们想要一个api变量,然后是JSON数据,然后是错误代码(或者成功代码取决于是否一切顺利).示例输出将是:

请输入api值作为参数(注意如果需要,这也可以是JSON)

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

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


带参数的url看起来像这样

http://localhost:8080/gotech/api/v1/api/3000105000
Run Code Online (Sandbox Code Playgroud)

我到目前为止的代码:

@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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 61

A @RestController不适合这个.如果需要返回不同类型的响应,请使用ResponseEntity<?>可以显式设置状态代码的位置.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要在带注释的类中@ResponseBody使用@RequestMapping方法@RestController.


Aff*_*ffe 31

惯用的方法是使用异常处理程序而不是在常规请求处理方法中捕获异常.异常类型确定响应代码.(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();
}
Run Code Online (Sandbox Code Playgroud)