Accessing query parameters using @QueryParam
In this entry, we will use the HelloWorldWebApp created in the previous entry. We will modify the resource, so that it takes name of a person as a query parameter and greets him/her. If no name is provided, it will give the general Hello World! message.
And here are the steps:
- Overwrite the previously implemented sayHello method with the following:
@GET
@Produces("text/plain")
public String sayHello(@QueryParam("name") String name) {
if (name != null) {
// if the query parameter "name" is there
return "Hello " + name + "!";
}
return "Hello World!";
}
- Import the class javax.ws.rs.QueryParam.
- Redeploy the application and enter http://localhost:8080/HelloWorldWebapp/resources/hello?name=Rama in a browser. You will see that response Hello Rama!. If the query parameter name is not specified the response would be Hello World!.
So how does this work?
Here we are using a new annotation @QueryParam. It is an annotation provided by the JAX-RS API. This annotation takes care of mapping a query parameter in a request to a method parameter.
In this example, we have used this annotation to map the query parameter name to the method parameter name. When a request is sent for the resource with some query parameter value for name, it gets set to the method parameter. For this to happen, the query parameter needs to be mapped to the method parameter. This is done by prefixing the method parameter declaration with @QueryParam and specifying the query parameter name as a string parameter for the annotation. In our example, it is achieved by doing this:
public String sayHello(@QueryParam("name") String name) {
Hello
I use your example with glasfish but queryPram give me this error :
Exception in thread "main" java.lang.NoSuchMethodError: com.sun.jersey.api.client.WebResource.queryParam(Ljava/lang/String;Ljava/lang/String;)Lcom/sun/jersey/api/client/WebResource;
Can you help me ?
Thank's
Christian
Posted by christian vial on April 14, 2009 at 06:16 AM PDT #
Yup, like the last guy, there is no such method as queryParam in webResource???? GRRRRR!!!!!
Posted by Confused coder on May 08, 2009 at 04:23 AM PDT #
I mean queryParams
Posted by Confused coder on May 08, 2009 at 04:25 AM PDT #
Which version of Jersey are you using?
The latest version does have this method.
Posted by Naresh on June 29, 2009 at 04:29 AM PDT #