@FormParam doesn't work with GET-RestEasy method
I am learning web services using Resteasy
I'm just doing a simple basic rest example using @FormParam
. My example works when the request method POST
but doesn't 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();
}
}
output with GET -
addUser is called, name: null, age: 0
output with POST -
addUser is called, name: Abhi, age: 23
Jsp request for GET
<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>
And Jsp request for POST
<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>
My question is, why can't I get the values ββusing a GET request with @FormParam
?
source to share
The default behavior of forms for GET requests is to put the key / values ββin the query string. If you look at the URL bar, you can see something like
http://localhost:8080/app/form/addUser?name=something&age=100
Unlike a POST request, this file name=something&age=100
will actually be in the body of the request and not in the URL. It @FormParam
works here , as for the data type application/x-www-form-urlencoded
, like body. The GET request should not have any body, so the data is sent to the URL.
To make the GET request work, we need another annotation that works with query strings. This annotation @QueryParam
. So just replace @FormParam("name")
with @QueryParam("name")
and the same with age
source to share