问题描述
我正在尝试使用@RestController
来接受@PathVariable
返回JSON格式的特定对象以及正确的状态代码.到目前为止,代码的方式是,它将以JSON格式返回对象,因为默认情况下,它使用的是Jackson库中内置的Spring 4.
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 Jackson library by default.
但是我不知道如何做到这一点,因此它将向用户显示一条消息,要求我们使用api变量,然后是JSON数据,然后是错误代码(或者是否成功,取决于是否一切正常).输出示例为:
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:
{"id":2,"api":"3000105000" ...}(注意,这将是JSON响应对象)
{"id": 2, "api": "3000105000" ... } (NOTE this will be the JSON response object)
状态码400(或正确的状态码)
Status Code 400 (OR proper status code)
带有参数的url看起来像这样
The url with parameter look like this
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;
}
}
}
推荐答案
@RestController
不适用于此情况.如果需要返回不同类型的响应,请使用ResponseEntity<?>
在其中可以显式设置状态代码.
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.
ResponseEntity
的body
的处理方式与任何@ResponseBody
带注释的方法的返回值相同.
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);
}
}
请注意,在@RestController
带注释的类中的@RequestMapping
方法上不需要@ResponseBody
.
Note that you don't need @ResponseBody
on a @RequestMapping
method within a @RestController
annotated class.
这篇关于Spring MVC @RestController @ResponseBody类中如何使用HTTP状态代码响应以返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!