使用javax的Reponse返回信息

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) {
        // 通过status()方法设置状态码,通过entity()设置返回的具体信息
        return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
    }
    return Response.ok().entity(exist).build();
}
  • 通过swagger查看response的具体内容
  1. 请求成功
{
  "statusType": "OK",
  "entity": {
    "id": 8,
    "name": "jack",
    "age": 22,
    "classId": 201306
  },
  "entityType": "example.lucy.com.demo.entity.Student",
  "metadata": {},
  "status": 200
}
  1. 请求失败
{
  "statusType": "BAD_REQUEST",
  "entity": "There is no student named cherry.",
  "entityType": "java.lang.String",
  "metadata": {},
  "status": 400
}
  • 总结: 在Spring boot项目中使用Response向客户端返回信息非常方便!
2. 使用Response类
  • 在maven中添加以下两个依赖即可
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>jsr311-api</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- 不添加该依赖,运行会报错: ClassNotFound Exception : com.sun.ws.rs.ext.RuntimeDelegateImpl -->
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.19</version>
</dependency>
  • 后来有一次,使用如下maven也ok了
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>2.32</version>
</dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值