Jersey Response响应请求

来源:互联网 发布:springmvc处理json 编辑:程序博客网 时间:2024/05/22 10:43

Chapter2-3 Jersey Response响应请求

前面介绍的Jersey示例,是根据实际需求返回结果,但我们实际在开发中一般不采用这种方式进行开发,在响应客户端请求时,我们使用Response进行响应请求。
javax.ws.rs.core.Response 官方Response Api

Response设置响应状态码

前面的示例中默认都是响应状态码是200,通过Response类,我们可以很方便的根据我们需求响应不同的状态码。
在Response 类中有内部的静态枚举Status,用于描述不同的响应状态码。常用的有。
OK(200, “OK”), 请求成功 需要我们手动响应
NO_CONTENT(204, “No Content”),无返回数据
BAD_REQUEST(400, “Bad Request”),请求错误 一般由于请求参数有误造成 需要我们手动响应
UNAUTHORIZED(401, “Unauthorized”),无权限 一般是由于没有登陆 需要我们手动响应
FORBIDDEN(403, “Forbidden”), 被禁止,无权限,一般是由于没有设置访问权限 需要我们手动响应
NOT_FOUND(404, “Not Found”), 未找到路径
METHOD_NOT_ALLOWED(405, “Method Not Allowed”),
INTERNAL_SERVER_ERROR(500, “Internal Server Error”),服务器异常 需要我们手动响应

@GET@Path("/getAll")public Response getAllBad(String userId){    try {        if(userId == null){            //请求参数有误,响应400 错误请求            return Response.status(Response.Status.BAD_REQUEST).build();        }        List<Student> lists = new ArrayList<Student>(map.values());    }catch (Exception e){        //当服务器抛出异常时会响应500        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();    }    //正常响应200    return Response.status(Response.Status.OK).build();}

上面的示例代码中,当请求参数userId为空时,服务器会响应400,当服务器抛出异常时,服务器会响应500,当一切响应正常时,服务器响应200。

Response响应JSON数据

在RESTful服务中,通常服务器是通过json数据与客户端进行交互的,下面介绍Jersey如何响应json数据的。
Response.entity()可以用于设置返回的数据。
本次示例使用阿里巴巴的fastjosn,在pom文件中引入fastjson的依赖。当然Jersey框架中也提供了自己的JSON工具,但开发中习惯使用Fastjson。

<dependency>  <groupId>com.alibaba</groupId>  <artifactId>fastjson</artifactId>  <version>1.2.21</version>  <type>pom</type></dependency>

RESTful服务

@GET@Path("/getAllByJson")public Response getAllJson(){    List<Student> lists = new ArrayList<Student>();    lists.add(new Student("1","mayun",23));    lists.add(new Student("2","mahuateng",24));    lists.add(new Student("3","zhouhongyi",25));    JSONObject json = new JSONObject();    return Response.status(Response.Status.OK).entity( json.toJSONString(lists)).build();}

访问http://localhost:8080/student/getAllByJson,返回对应的josn数据

[    {        "age": 23,        "id": "1",        "name": "mayun"    },    {        "age": 24,        "id": "2",        "name": "mahuateng"    },    {        "age": 25,        "id": "3",        "name": "zhouhongyi"    }]

Response设置响应类型

Response.type(“application/json”);
可以根据具体需要设置不同的响应类型

Response实现跳转

Response实现跳转有两种方式:

  1. 保留请求方式
@POST@Path("/jump2")public Response jump(){    String url = "http://www.baidu.com";    return Response.temporaryRedirect(URI.create(url)).build();}

Response.temporaryRedirect(URI.create(url)).build();这样是跳转到指定路径,需要注意的是这个方法的跳转方式GET,POST等会延用进入该方法时的方法,如果是POST方法进入的那么跳转后的方法还是post。
2. GET请求方式

/** * 请求方式变为GET * @return */@GET@Path("/jump")public Response redict(){    String url = "http://www.baidu.com";    return   Response.seeOther(URI.create(url)).build();}

Response.seeOther(URI.create(url)).build().上面的示例中访问/jump ,可以跳转到百度首页,需要注意的是通过这种方式跳转url路径必须是完整的,也即要带着对应的协议。

Response工具类

对于Response使用我们可以提出一个常用的工具类,下面分享下我们使用的,供大家参考。
只是关于响应的工具类。

public class JerseyTool {    public static Response returnUnauthorized() {        return Response.status(Status.UNAUTHORIZED).build();    }    public static Response returnAbort(String errorJson) {        return Response.status(Status.BAD_REQUEST).entity(errorJson).type("application/json").build();    }    public static Response returnServerError(String errorJson) {        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorJson).type("application/json").build();    }    public static Response returnSuccess(String json) {        return json != null?Response.status(Status.OK).entity(json).type("application/json").build():Response.status(Status.OK).build();    }    public static Response returnSuccess() {        return Response.status(Status.OK).build();    }}

前面介绍了Response的基本使用,基本可以满足在日常开发时的大量场景,如需其他资料请参考官方Response Api。

Jersey系列相关源码请访问:Jersey_learing项目

0 0