简体   繁体   English

在Java(JAX-RS)中的POST请求上接收未知的参数名称

[英]Receiving unknown parameter name on POST request in Java (JAX-RS)

I have the following POST response in JAX-RS. 我在JAX-RS中具有以下POST响应。

@POST
@Path("/save")
public Response saveS(@FormParam(key) String value) throws SQLException {           
    return Response.ok("TODO", MediaType.APPLICATION_JSON).build();
}

The parameter that is received could be called name or age or many other things. 接收到的参数可以称为nameage或许多其他内容。 I have identified it as key in the code (obviously it doesn't work). 我已经在代码中将其标识为key (显然它不起作用)。

How can I retrieve the name of that parameter? 如何检索该参数的名称?

Thanks 谢谢

The parameter that is received could be called name or age or many other things. 接收到的参数可以称为名称或年龄或许多其他内容。 I have identified it as key in the code (obviously it doesn't work). 我已经在代码中将其标识为键(显然它不起作用)。

As you already found out it doesn't work that way because the @FormParam is expecting the name of a form parameter as it is defined in the corresponding HTML form. 正如您已经发现的那样,该方法行不通,因为@FormParam期望使用在相应HTML表单中定义的表单参数名称。 That means you should know which form parameter you want to assign to the param ( value in this case) of the method. 这意味着您应该知道要分配给该方法的参数(在这种情况下为value )的表单参数。

Here is the definition of the @FormParam annotation extracted from the JAX-RS specification : 这是从JAX-RS规范中提取的@FormParam批注的定义:

FormParam Parameter FormParam参数

Specifies that the value of a method parameter is to be extracted from a form parameter in a request entity body. 指定要从请求实体主体中的表单参数中提取方法参数的值。 The value of the annotation identifies the name of a form parameter. 注释的值标识表单参数的名称。 Note that whilst the annotation target allows use on fields and methods, the specification only requires support for use on resource method parameters. 请注意,虽然注释目标允许在字段和方法上使用,但规范仅要求支持对资源方法参数的使用。

And in addition to that you should add the @Consumes annotation to your resource method as follows: 除此之外,还应将@Consumes批注添加到资源方法中,如下所示:

@POST
@Path("/save")
@Consumes("application/x-www-form-urlencoded")
public Response saveS(@FormParam(key) String value) throws SQLException {           
    return Response.ok("TODO", MediaType.APPLICATION_JSON).build();
}

Update: I haven't tried myself, but you can try and tell me if it works. 更新:我还没有尝试过,但是您可以尝试告诉我是否可行。 Here you should get all the params so that you can parse all the form fields: 在这里,您应该获取所有参数,以便可以解析所有表单字段:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
   // parse the map here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM