jersey常用的注解类型

HTTP Methods

HTTP方法映射到资源的CRUD(创建、读取、更新和删除)操作,基本模式如下:

  • HTTP GET:读取/列出/检索单个或资源集合。
  • HTTP POST:新建资源。
  • HTTP PUT:更新现有资源或资源集合。
  • HTTP DELETE:删除资源或资源集合。


1.@Produces

@Produces注释用来指定将要返回给client端的数据标识类型(MIME)。 @Produces可以作为class注释,也可以作为方法注释,方法的 @Produces注释将会覆盖class的注释。


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;
	}


2.@Consumes

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

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

@Consumes(MediaType.TEXT_PLAIN)

b.接受clent参数为json类型

@Consumes(MediaType.APPLICATION_JSON)


3.请求参数注解

@PathParam

     获取url中指定参数名称:

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

请求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) {
    ...
}



当浏览器请求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) {
    ...
}


@FormParam
         获取post请求中表单中的数据:
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
    // Store the message
}

@BeanParam
        获取请求参数中的数据,用实体Bean进行封装:
@POST
@Consumes("application/x-www-form-urlencoded")
public void update(@BeanParam User user) {
    // Store the user data
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值