Java 如何访问HttpServletRequest中的POST参数?
我有一个基本上是服务代理的应用程序。该应用程序本身建立在泽西岛上,由Jetty提供服务。我有这个资源方法:Java 如何访问HttpServletRequest中的POST参数?,java,http,jersey,jetty,Java,Http,Jersey,Jetty,我有一个基本上是服务代理的应用程序。该应用程序本身建立在泽西岛上,由Jetty提供服务。我有这个资源方法: @POST @Path("/{default: .*}") @Timed @Consumes("application/x-www-form-urlencoded") public MyView post(@Context UriInfo uriInfo, @Context HttpServletRequest request) { ... } 用户提交一个POST表单。所有POST
@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正文显然包含两个参数:foo和biz。但是当我尝试在代码中获取它们时(request.getParameterMap
),结果是一个大小为0的映射
如何从资源方法内部访问这些参数或此参数字符串?如果重要的话,使用的HttpServletRequest
的实现是org.eclipse.jetty.server.Request。三个选项
@FormParam(“”)
到gt单个参数。前
@POST
@Consumes("application/x-www-form-urlencoded")
public Response post(@FormParam("foo") String foo
@FormParam("bar") String bar) {}
多值映射
获取所有参数
@POST
@Consumes("application/x-www-form-urlencoded")
public Response post(MultivaluedMap<String, String> formParams) {
String foo = formParams.getFirst("foo");
}
@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) {
}
谢谢多值地图正是我所需要的。阅读本文的其他人请注意:在多值映射上使用
@Context
会导致它为空。该值只在没有@Context
注释的情况下被注入…回答得很好…节省了我的时间,多值映射是我正在寻找的,它没有@Context
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) {
}