restful裏的resource類裏的各種接收參數方式

一開始用的是@QueryParam來接收參數,後來學習中發現有@PathParam也可以接收,但是用法不一樣,擺渡後,自己在這裏做了總結:

一、@PathParam (@PathParam ,url中直接在斜槓後面添加參數值

如,http://localhost:8181/managerinfo/rs/helloworld/user/frank

而resource裏的寫法是:

@GET
	@Path("/user/{condition}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.TEXT_HTML)
	public String getHelloWithPath(@PathParam("condition") String username) {
		return "Hello Path UserName " + username;
	}
二、 @QueryParam  (url中在後面添加【鍵值對】形式的參數

如:用ajax請求 

$.ajax({
             type: 'GET',
             contentType: "application/json",
             dataType: 'html',
             url: 'http://localhost:8181/managerinfo/rs/helloworld/user',
             data: {
                  username:"frank"
	     },
	     success:function(data){
	          alert(data);
	     }

實際請求地址會是:http://localhost:8181/managerinfo/rs/helloworld/user?username=frank

以下幾種寫法,轉載於:

http://blog.csdn.net/azhegps/article/details/72782704

這裏自己沒用過,記錄下:

三、@DefaultValue

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

當瀏覽器請求http://host:port/user?name=rose時,name值爲rose,age值爲26。 

四、@FormParam 
@FormParam,顧名思義,從POST請求的表單參數中獲取數據。如: 
@POST 
@Consumes("application/x-www-form-urlencoded") 
publicvoid post(@FormParam("name") String name) { 
    // Store the message 

相信使用過html進行post提交的人對錶單一定不陌生,可以想象成這就是在模擬html中表單的請求。 
五、使用Map 
在一個大型的server中,因爲參數的多變,參數結構的調整都會因爲以上幾種方式而遇到問題,這時可以考慮使用@Context 註釋,並獲取UriInfo實例,如下: 
@GET 
public String get(@Context UriInfo ui) { 
    MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); 
    MultivaluedMap<String, String> pathParams = ui.getPathParameters(); 

我覺得,可以認爲map是上面幾種情況的超集,因爲它能夠替代以上任意一種。map就是context 

同樣還可以通過@Context 註釋獲取ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse和HttpHeaders等,如下: 
@Path("/") 
publicclass Resource { 

    @Context 
    HttpServletRequest req; 

    @Context 
    ServletConfig servletConfig; 

    @Context 
    ServletContext servletContext; 

    @GET 
    public String get(@Context HttpHeaders hh) { 
        MultivaluedMap<String, String> headerParams = hh.getRequestHeaders(); 
        Map<String, Cookie> pathParams = hh.getCookies(); 
    } 
}  





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章