我必须更新具有名字和姓氏的个人记录。用户应该能够从 html 表单更改它,并在提交时更新它。
这是我的代码。
@PUT
@Path("/{userId}")
public Response updatingResource(@FormParam("firstName") String firstName, @FormParam("lastName ") String lastName , @PathParam("userId") String userId){
System.out.println(firstName);
System.out.println(lastName);
return Response.ok().build();
}
SOP 语句打印 null。我一直在使用 Mozilla Firefox 的 Poster 插件来发送 PUT 请求。
我也尝试用 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
注释它,但它仍然为每个值打印 null。
如何编写和调用接收这三个值的 PUT 方法。我偶然发现很多人要求使用 JSON 或 XML。我如何使用 JSON?如果有人帮助我编写 REST 方法来更新资源,我将非常感激
如果我使用 Firefox 的 RESTClient 发送 PUT 请求和谷歌的 rest-client我能够获取表单参数。这两个工具都有类似正文部分的东西,我在其中放置了 firstName=Amit&lastName=Patel
。我还添加了 header Content-Type
作为 application/x-www-form-urlencoded
。我认为 Firefox 的 Poster是 buggy 。谁能建议我有没有其他方法可以验证代码,或者我可以信任前两个 REST 客户端?
最佳答案
除了使用 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
注释您的方法之外,您还必须发送 application/x-www-form-urlencoded
作为内容类型。你做到了吗?
已编辑:您只能将 FormParams 与 POST 一起使用:
SRV.4.1.1 When Parameters Are Available The following are the conditions that must be met before post form data will be populated to the parameter set:
- The request is an HTTP or HTTPS request.
- The HTTP method is POST.
- The content type is application/x-www-form-urlencoded.
- The servlet has made an initial call of any of the getParameter family of methods on the request object. If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request object’s input stream. If the conditions are met, post form data will no longer be available for reading directly from the request object’s input stream.
关于java - 带有 Jersey : Passing form parameters to PUT method for updating a Resource 的 JAX-RS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5964122/