javax.​ws.​rs注解:@Conumes 和 @Produces等

1、概述

@Consumes 注释代表的是一个资源可以接受的 MIME 类型。

@Produces 注释代表的是一个资源可以返回的 MIME 类型。

这些注释均可在资源、资源方法、子资源方法、子资源定位器或子资源内找到。


2、@Produces:返回的类型

a.返回给client字符串类型(text/plain)

@Produces(MediaType.TEXT_PLAIN) 

b.返回给client为json类型(application/json)

@Produces(MediaType.APPLICATION_JSON) 

测试:

string类型:

  1. @Path("/say")
  2. @GET
  3. @Produces(MediaType.TEXT_PLAIN)
  4. public String say() {
  5. System.out.println("hello world");
  6. return "hello world";
  7. }

json和bean类型:

  1. @Path( "test")
  2. @GET
  3. @Produces(MediaType.APPLICATION_JSON)
  4. public Result<String> test() {
  5. Result<String> result = new Result<String>();
  6. result.success( "aaaaaa");
  7. return result;
  8. }
  9. @Path( "bean")
  10. @GET
  11. @Produces(MediaType.APPLICATION_JSON)
  12. public UserBean bean() {
  13. UserBean userBean = new UserBean();
  14. userBean.setId( 1);
  15. userBean.setUsername( "fengchao");
  16. return userBean;
  17. }

3、@Consumes

@Consumes@Produces相反,用来指定可以接受client发送过来的MIME类型,同样可以用于class或者method,也可以指定多个MIME类型,一般用于@PUT@POST

a.接受client参数为字符串类型

@Consumes(MediaType.TEXT_PLAIN)  b.接受clent参数为json类型@Consumes(MediaType.APPLICATION_JSON) 

其他注解:

@PathParam

获取url中指定参数名称:

[java]  view plain  copy
  1. <code class="language-java">@GET    
  2. @Path("{username"})    
  3. @Produces(MediaType.APPLICATION_JSON)    
  4. public User getUser(@PathParam("username") String userName) {    
  5.     ...    
  6. }  </code>  

@QueryParam
 
获取get请求中的查询参数:  
  1. @GET
  2. @Path( "/user")
  3. @Produces( "text/plain")
  4. public User getUser(@QueryParam("name") String name,
  5. @QueryParam("age") int age) {
  6. ...
  7. }

如果需要为参数设置默认值,可以使用@DefaultValue,如:
  1. @GET
  2. @Path( "/user")
  3. @Produces( "text/plain")
  4. public User getUser(@QueryParam("name") String name,
  5. @DefaultValue("26") @QueryParam("age") int age) {
  6. ...
  7. }

@FormParam
 获取post请求中表单中的数据:
  1. @POST
  2. @Consumes( "application/x-www-form-urlencoded")
  3. public void post(@FormParam("name") String name) {
  4. // Store the message
  5. }
@BeanParam
 获取请求参数中的数据,用实体Bean进行封装
  1. @POST
  2. @Consumes( "application/x-www-form-urlencoded")
  3. public void update(@BeanParam User user) {
  4. // Store the user data
  5. }

转载至:https://blog.youkuaiyun.com/zhengchao1991/article/details/54375626

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值