1.绪言
javax.ws.rs.core.Response
的Response类定义了很多符合HTTP规范的状态码,还以通过entity()
方法向客户端返回任意类型的数据。- 基于spring boot,使用Response类代码示例如下:
@GetMapping("/testResponse")
public Response testResponse(@RequestParam(name = "name") String name) {
Student exist = null;
try {
exist = studentService.findByName(name);
} catch (Exception exception) {
return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
}
return Response.ok().entity(exist).build();
}
- 请求成功
{
"statusType": "OK",
"entity": {
"id": 8,
"name": "jack",
"age": 22,
"classId": 201306
},
"entityType": "example.lucy.com.demo.entity.Student",
"metadata": {},
"status": 200
}
- 请求失败
{
"statusType": "BAD_REQUEST",
"entity": "There is no student named cherry.",
"entityType": "java.lang.String",
"metadata": {},
"status": 400
}
- 总结: 在Spring boot项目中使用Response向客户端返回信息非常方便!
2. 使用Response类
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.32</version>
</dependency>