簡體   English   中英

如何在HttpServletRequest中訪問POST參數?

[英]How to access POST parameters in HttpServletRequest?

我有一個基本上是服務代理的應用程序。 該應用程序本身建在澤西島上,由Jetty提供服務。 我有這個資源方法:

@POST
@Path("/{default: .*}")
@Timed
@Consumes("application/x-www-form-urlencoded")
public MyView post(@Context UriInfo uriInfo, @Context HttpServletRequest request) {
  ...
}

用戶提交POST表單。 所有POST請求都通過此方法。 除了一個細節之外,UriInfo和HttpServletRequest被適當地注入:似乎沒有參數。 這是我從終端發送的請求:

POST /some/endpoint HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 15
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8010
User-Agent: HTTPie/0.9.2

foo=bar&biz=baz

POST主體顯然包含2個參數:foo和biz。 但是當我嘗試在我的代碼( request.getParameterMap )中獲取它們時,結果是一個大小為0的映射。

如何從資源方法中訪問這些參數或此參數字符串? 如果重要,使用的HttpServletRequest的實現是org.eclipse.jetty.server.Request。

三種選擇

  1. @FormParam("<param-name>") gt個別參數。 防爆。

     @POST @Consumes("application/x-www-form-urlencoded") public Response post(@FormParam("foo") String foo @FormParam("bar") String bar) {} 
  2. 使用MultivaluedMap來獲取所有參數

     @POST @Consumes("application/x-www-form-urlencoded") public Response post(MultivaluedMap<String, String> formParams) { String foo = formParams.getFirst("foo"); } 
  3. 使用Form獲取所有參數。

     @POST @Consumes("application/x-www-form-urlencoded") public Response post(Form form) { MultivaluedMap<String, String> formParams = form.asMap(); String foo = formParams.getFirst("foo"); } 
  4. 使用@BeanParam和單獨的@FormParam來獲取bean中的所有單個參數。

     public class FormBean { @FormParam("foo") private String foo; @FormParam("bar") private String bar; // getters and setters } @POST @Consumes("application/x-www-form-urlencoded") public Response post(@BeanParam FormBean form) { } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM