真实世界中比较著名的 REST 服务包括:Google AJAX 搜索 API、Amazon Simple Storage Service (Amazon S3) 等。
com.sun.jersey.spi.container.servlet.ServletContainer
@Path("UserContext") 类和方法
@Path("/accounts/{beginDate://d{4}-//d{2}-//d{2}},{endDate://d{4}-//d{2}-//d{2}}/") @PathParam("beginDate")
@QueryParam("org")
@DefaultValue("默认组织")
@Singleton @PerSession
@Produces("application/xml")
@Consumes("text/plain")
@GET、@POST、@PUT、@DELETE 或者自定义的 @HttpMethod
Java EE 6包含
Servlet 3.0
JSF 2.0
WebBeans
CDI (Contexts and Dependency Injection)
Bean Validation
EJB 3.1
JPA 2.0
JAX-RS
JAX-RS 依赖于 MessageBodyReader 和 MessageBodyWriter 的实现来自动完成返回值到响应体的序列化以及请求体到实体参数的反序列化工作,其中,XML 格式的请求/响应数据与 Java 对象的自动绑定依赖于 JAXB 的实现。
@Provider @Produces("application/json") @Consumes("application/json") public class GsonProvider implements MessageBodyWriter<Object>, MessageBodyReader<Object> { private final Gson gson; public GsonProvider() { gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat( "yyyy-MM-dd").create(); } public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { return gson.fromJson(new InputStreamReader(entityStream, "UTF-8"), type); } public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } public long getSize(Object obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public void writeTo(Object obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(gson.toJson(obj, type).getBytes("UTF-8")); } }
esource 方法合法的参数类型包括:
- 原生类型
- 构造函数接收单个字符串参数或者包含接收单个字符串参数的静态方法 valueOf 的任意类型
- List<T>,Set<T>,SortedSet<T>(T 为以上的 2 种类型)
- 用于映射请求体的实体参数
Resource 方法合法的返回值类型包括:
- void:状态码 204 和空响应体
- Response:Response 的 status 属性指定了状态码,entity 属性映射为响应体
- GenericEntity:GenericEntity 的 entity 属性映射为响应体,entity 属性为空则状态码为 204,非空则状态码为 200
- 其它类型:返回的对象实例映射为响应体,实例为空则状态码为 204,非空则状态码为 200
对于错误处理,Resource 方法可以抛出非受控异常 WebApplicationException 或者返回包含了适当的错误码集合的 Response 对象。