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

时间:2014-10-01 04:51:39

标签: java json spring spring-mvc

我正在尝试使用@RestController@PathVariable返回JSON格式的特定对象以及正确的状态代码。到目前为止,代码的方式是,它将以JSON格式返回对象,因为默认情况下它使用的是Spring库中内置的Spring 4。

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

  

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

     

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

     

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


带参数的网址如下所示

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

2 个答案:

答案 0 :(得分:61)

@RestController不适用于此。如果您需要返回不同类型的回复,请使用ResponseEntity<?>,您可以在其中明确设置状态代码。

body的{​​{1}}将以与任何ResponseEntity带注释的方法的返回值相同的方式处理。

@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

答案 1 :(得分:30)

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