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

1.概述

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

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

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

2.@Produces:返回的类型

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

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

@Produces(MediaType.APPLICATION_JSON) 

测试:

string类型:

 @Path("/say")  
    @GET  
    @Produces(MediaType.TEXT_PLAIN)  
    public String say() {  
        System.out.println("hello world");  
        return "hello world";     
    }

json和bean类型:

  @Path("test")  
    @GET  
    @Produces(MediaType.APPLICATION_JSON)  
    public Result<String> test() {  
        Result<String> result = new Result<String>();  
        result.success("aaaaaa");  
          
        return result;  
    }  
      
    @Path("bean")  
    @GET  
    @Produces(MediaType.APPLICATION_JSON)  
    public UserBean bean() {  
        UserBean userBean = new UserBean();  
        userBean.setId(1);  
        userBean.setUsername("fengchao");  
        return userBean;  
    }

3.@Consumes

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

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

@Consumes(MediaType.TEXT_PLAIN)

b.接受client参数为json类型

@Consumes(MediaType.APPLICATION_JSON)

4.请求参数注解

(1)@PathParam

       1) 获取URL中指定参数名称:

@GET
@Path("{username"})
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("username") String userName) {
    ...
}

    2)请求url:http://localhost/user/jack时,userName值为jack @QueryParam

            获取get请求中的查询参数:

@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
                     @QueryParam("age") int age) {
    ...
}

3.当浏览器请求http://host:port/user?name=rose&age=25时,name值为rose,age值为25。如果需要为参数设置默认值,可以使用@DefaultValue,如:

@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
                    @DefaultValue("26") @QueryParam("age") int age) {
    ...
}

(2)@FormParam

            获取post请求中表单中的数据:

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

(3)@BeanParam

        获取请求参数中的数据,用实体Bean进行封装:

@POST
@Consumes("application/x-www-form-urlencoded")
public void update(@BeanParam User user) {
    // Store the user data
}

猜你喜欢

转载自blog.csdn.net/shizhudufou/article/details/80996462
今日推荐