Java 如何在返回对象的 Spring MVC @RestController @ResponseBody 类中使用 HTTP 状态代码进行响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26134331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to respond with HTTP status code in a Spring MVC @RestController @ResponseBody class returning an object?
提问by Cris
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 the way the code is, it will return the object in JSON format because it is using Spring 4 built in Hymanson library by default.
我想有一个@RestController
,这需要@PathVariable
以JSON格式返回一个特定的对象,适当的状态代码一起。到目前为止代码的方式,它将以JSON格式返回对象,因为它默认使用Hymanson库中内置的Spring 4。
However I do not know how to make it so it will give a message to the user saying we want an api variable, then JSON data, then Error code (Or success code depending if all went well). Example output would be:
但是我不知道如何制作它,所以它会向用户发出一条消息,说我们想要一个 api 变量,然后是 JSON 数据,然后是错误代码(或成功代码,取决于一切是否顺利)。示例输出将是:
Please enter api value as parameter (NOTE this can be in JSON as well if needed)
{"id": 2, "api": "3000105000" ... } (NOTE this will be the JSON response object)
Status Code 400 (OR proper status code)
请输入 api 值作为参数(注意,如果需要,这也可以是 JSON)
{"id": 2, "api": "3000105000" ... } (注意这将是 JSON 响应对象)
状态代码 400(或正确的状态代码)
The url with parameter look like this
带有参数的 url 看起来像这样
http://localhost:8080/gotech/api/v1/api/3000105000
The code I have so far:
我到目前为止的代码:
@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;
}
}
}
采纳答案by Sotirios Delimanolis
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.
A@RestController
不适合这个。如果您需要返回不同类型的响应,请使用ResponseEntity<?>
可以显式设置状态代码的地方。
The body
of the ResponseEntity
will be handled the same way as the return value of any @ResponseBody
annotated method.
的body
的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);
}
}
Note that you don't need @ResponseBody
on a @RequestMapping
method within a @RestController
annotated class.
请注意,您不需要注释类中@ResponseBody
的@RequestMapping
方法@RestController
。
回答by Affe
The idiomatic way would be to use an exception handler instead of catching the exception in your regular request handling method. The type of exception determines the response code. (403 for security error, 500 for unexpected platform exceptions, whatever you like)
惯用的方法是使用异常处理程序,而不是在常规请求处理方法中捕获异常。异常的类型决定了响应代码。(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();
}