HTTP方法映射到资源的CRUD(创建、读取、更新和删除)操作,基本模式如下:
@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";
}
@Path("test")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Result test() {
Result result = new Result();
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;
}
@Consumes
与
@Produces
相反,用来指定可以接受client发送过来的MIME类型,同样可以用于class或者method,也可以指定多个MIME类型,一般用于
@PUT
,
@POST
a.接受client参数为字符串类型
@Consumes(MediaType.TEXT_PLAIN)
b.接受clent参数为json类型
@Consumes(MediaType.APPLICATION_JSON)
获取url中指定参数名称:
@GET
@Path("{username"})
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("username") String userName) {
...
}
@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
@QueryParam("age") int age) {
...
}
@DefaultValue
,如:
@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
@DefaultValue("26") @QueryParam("age") int age) {
...
}
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
// Store the message
}
@POST
@Consumes("application/x-www-form-urlencoded")
public void update(@BeanParam User user) {
// Store the user data
}