简体   繁体   English

如何在HttpServletRequest中访问POST参数?

[英]How to access POST parameters in HttpServletRequest?

I've got an app that's basically a proxy to a service. 我有一个基本上是服务代理的应用程序。 The app itself is built on Jersey and served by Jetty. 该应用程序本身建在泽西岛上,由Jetty提供服务。 I have this Resource method: 我有这个资源方法:

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

A user submits a POST form. 用户提交POST表单。 All POST requests go through this method. 所有POST请求都通过此方法。 The UriInfo and HttpServletRequest are injected appropriately except for one detail: there seem to be no parameters. 除了一个细节之外,UriInfo和HttpServletRequest被适当地注入:似乎没有参数。 Here is my request being sent from the terminal: 这是我从终端发送的请求:

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

Here the POST body clearly contains 2 parameters: foo and biz. POST主体显然包含2个参数:foo和biz。 But when I try to get them in my code ( request.getParameterMap ) the result is a map of size 0. 但是当我尝试在我的代码( request.getParameterMap )中获取它们时,结果是一个大小为0的映射。

How do I access these parameters or this parameter string from inside my resource method? 如何从资源方法中访问这些参数或此参数字符串? If it matters, the implementation of HttpServletRequest that is used is org.eclipse.jetty.server.Request. 如果重要,使用的HttpServletRequest的实现是org.eclipse.jetty.server.Request。

Three options 三种选择

  1. @FormParam("<param-name>") to gt individual params. @FormParam("<param-name>") gt个别参数。 Ex. 防爆。

     @POST @Consumes("application/x-www-form-urlencoded") public Response post(@FormParam("foo") String foo @FormParam("bar") String bar) {} 
  2. Use a MultivaluedMap to get all the params 使用MultivaluedMap来获取所有参数

     @POST @Consumes("application/x-www-form-urlencoded") public Response post(MultivaluedMap<String, String> formParams) { String foo = formParams.getFirst("foo"); } 
  3. Use Form to get all the params. 使用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. Use a @BeanParam along with individual @FormParam s to get all the individual params inside a bean. 使用@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