问题描述
我正在使用Resteasy学习Web服务
I am learning web services with Resteasy
我正在使用@FormParam
做一个简单的休息简单示例.我的示例在请求方法为POST
时有效但是当我将请求方法更改为GET
i am doing a simple basic example of rest easy using @FormParam
.My example works when request method is POST
but does not work when i change the request method toGET
@Path("/form")
public class FromParamService {
@POST
@Path("/add")
public Response addUser(
@FormParam("name") String name,
@FormParam("age") int age) {
return Response.status(200)
.entity("addUser is called, name : " + name + ", age : " + age)
.build();
}
@GET
@Path("/adduser")
public Response addUser1(
@FormParam("name") String name,
@FormParam("age") int age) {
return Response.status(200)
.entity("addUser is called, name : " + name + ", age : " + age)
.build();
}
}
使用GET的输出是
POST输出为
GET请求的jsp是
The jsp for GET request is
<html><body>
<form action="rest/form/adduser" method="get">
<p>
Name : <input type="text" name="name" />
</p>
<p>
Age : <input type="text" name="age" />
</p>
<input type="submit" value="Add User" />
</form></body></html>
用于POST请求的Jsp是
And Jsp for POST request is
<html><body>
<form action="rest/form/add" method="post">
<p>
Name : <input type="text" name="name" />
</p>
<p>
Age : <input type="text" name="age" />
</p>
<input type="submit" value="Add User" />
</form></body></html>
我的问题是为什么我无法使用@FormParam
的GET请求获取值?
My question is why i am not able to get values using GET request with @FormParam
?
推荐答案
用于GET请求的表单的默认行为是将键/值放在查询字符串.如果您在网址栏中查看,则可能会看到类似
The default behavior of forms for GET requests, is to put the key/values in the query string. If you look in the URL bar, you might see something like
http://localhost:8080/app/form/addUser?name=something&age=100
与POST请求相反,此oart name=something&age=100
实际上将在请求的正文中,而不是URL中.这是@FormParam
起作用的地方,对于application/x-www-form-urlencoded
数据类型也是如此. GET请求不应包含任何正文,因此数据将通过URL发送.
As opposed to POST request, this oart name=something&age=100
will actually be in the body of the request, not in the URL. This is where @FormParam
works, as it is for application/x-www-form-urlencoded
data type, as the body. GET request should have no body, so the data is send in the URL.
要使GET请求正常工作,我们需要一个与查询字符串配合使用的不同注释.该注释为@QueryParam
.因此,只需将@FormParam("name")
替换为@QueryParam("name")
,并根据年龄将其替换为
To get the GET request to work, we need a different annotation that works with query strings. That annotation is @QueryParam
. So just replace the @FormParam("name")
with @QueryParam("name")
and same for the age
这篇关于@FormParam不适用于GET方法-RestEasy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!