Jersey annotation examples

Jersey Tutor URL: https://jersey.java.net/

API URL: http://jax-rs-spec.java.net/nonav/2.0/apidocs/index.html?javax/ws/rs/Produces.html

#1. The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.

Specifying output MIME type

@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }
 
    @GET
    @Produces("text/html")
    public String doGetAsHtml() {
        ...
    }
}

#2. The @Consumes annotation is used to specify the MIME media types of representations that can be consumed by a resource.

Specifying input MIME type

@POST
@Consumes("text/plain")
public void postClichedMessage(String message) {
    // Store the message
}
In this example, the Java method will consume representations identified by the MIME media type "text/plain". Notice that the resource method returns void. This means no representation is returned and response with a status code of 204 (No Content) will be returned to the client.


#3. Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request.

#3.1 Use of @PathParam to extract a path parameter from the path component of the request URL that matched the path declared in@Path.

#3.2 @QueryParam is used to extract query parameters from the Query component of the request URL.

#3.3 The @PathParam and the other parameter-based annotations, @MatrixParam, @HeaderParam, @CookieParam, @FormParam obey the same rules as @QueryParam. @MatrixParam extracts information from URL path segments.


@HeaderParam extracts information from the HTTP headers.

@CookieParam extracts information from the cookies declared in cookie related HTTP headers.

@FormParam is slightly special because it extracts information from a request representation that is of the MIME media type"application/x-www-form-urlencoded" and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example the following extracts the form parameter named "name" from the POSTed form data:

Processing POSTed HTML form

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
    // Store the message
}


#4. @Context can be used to obtain contextual Java types related to the request or response.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值