微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Jersey创建RESTful风格的WebService

什么是RESTful架构

  • 一个URI代表一种资源
  • 客户端和服务端之间传递这种资源的某种表现层(“资源”具体呈现出来的形式叫做它的“表现层”。)
  • 对于资源的具体操作,由HTTP动词表示。客户端通过HTTP动词(GET,POST,PUT,DELETE)对服务端资源进行操作,实现表现层状态转换

JAX-RS annotations

Annotation Description
@PATH(your_path) Sets the path to base URL + /your_path. The base URL is based on your application name,the servlet and the URL pattern from the web.xml configuration file.
@POST Indicates that the following method will answer to an HTTP POST request.
@GET Indicates that the following method will answer to an HTTP GET request.
@PUT Indicates that the following method will answer to an HTTP PUT request.
@DELETE Indicates that the following method will answer to an HTTP DELETE request.
@Produces(MediaType.TEXT_PLAIN[,more-types]) @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text (“text/plain”) is produced. Other examples would be “application/xml” or “application/json”.
@Consumes(type[,more-types]) @Consumes defines which MIME type is consumed by this method.
@PathParam Used to inject values from the URL into a method parameter. This way you inject,for example,the ID of a resource into the method to get the correct object.

典型的设计误区

  • URI包含动词。“资源”是一种实体,应该是名词。URI不应该有动词,动词放在HTTP协议中。
  • URI中加入版本号。
    例如
    http://www.example.com/app/1.0/foo
    http://www.example.com/app/1.1/foo
    http://www.example.com/app/2.0/foo 不同的版本可以理解为同一种资源的不同表现形式,所以应该用同一个URI,版本号可以在HTTP请求头信息中的Accept字段中区分: Accept: vnd.example-com.foo+json; version=1.0 Accept: vnd.example-com.foo+json; version=1.1 Accept: vnd.example-com.foo+json; version=2.0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐