HTTP方法映射到資源的CRUD(創建、讀取、更新和刪除)操作,基本模式如下:
HTTP GET:讀取/列出/檢索單個或資源集合。
HTTP POST:新建資源。
HTTP PUT:更新現有資源或資源集合。
HTTP DELETE:刪除資源或資源集合。
1.@Produces
@Produces注釋用來指定將要返回給client端的數據標識類型(MIME)。@Produces可以作為class注釋,也可以作為方法注釋,方法的@Produces注釋將會覆蓋class的注釋。
a.返回給client字符串類型(text/plain)
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@Produces(MediaType.TEXT_PLAIN)
b.返回給client為json類型(application/json)
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@Produces(MediaType.APPLICATION_JSON)
測試:
string類型:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@Path("say")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String say() {
System.out.println("hello world");
return "hello world";
}
json和bean類型:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@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參數為字符串類型
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@Consumes(MediaType.TEXT_PLAIN)
b.接受clent參數為json類型
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@Consumes(MediaType.APPLICATION_JSON)
3.請求參數注解
@PathParam
獲取url中指定參數名稱:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@GET
@Path("{username"})
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("username") String userName) {
...
}
請求url:http://localhost/user/jack時,userName值為jack
@QueryParam
獲取get請求中的查詢參數:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@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,如:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
@DefaultValue("26") @QueryParam("age") int age) {
...
}
@FormParam
獲取post請求中表單中的數據:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
// Store the message
}
@BeanParam
獲取請求參數中的數據,用實體Bean進行封裝:
[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片
@POST
@Consumes("application/x-www-form-urlencoded")
public void update(@BeanParam User user) {
// Store the user data
}