使用javax的Reponse返回信息

    科技2026-01-13  9

    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的具体内容 请求成功 { "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类
    在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>
    Processed: 0.018, SQL: 9