@FormParam does not work with GET method-RestEasy

放肆的年华 提交于 2019-12-10 22:07:45

问题


I am learning web services with Resteasy

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();

    }
}

output with GET is

addUser is called, name : null, age : 0

output with POST is

addUser is called, name : Abhi, age : 23

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>

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>

My question is why i am not able to get values using GET request with @FormParam?


回答1:


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

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.

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



来源:https://stackoverflow.com/questions/29789801/formparam-does-not-work-with-get-method-resteasy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!