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) {

Comments:

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 13, 2009 at 11:16 PM PDT #

Yup, like the last guy, there is no such method as queryParam in webResource???? GRRRRR!!!!!

Posted by Confused coder on May 07, 2009 at 09:23 PM PDT #

I mean queryParams

Posted by Confused coder on May 07, 2009 at 09:25 PM PDT #

Which version of Jersey are you using?
The latest version does have this method.

Posted by Naresh on June 28, 2009 at 09:29 PM PDT #

I enter http://localhost:8080/HelloWorldWebapp/resources/hello?name=Joe and it returns Hello World! meaning that name is null. why? i'm using netbeans 6.8 and server.log shows "Running GlassFish Version: GlassFish v3 (build 74.2)"

Posted by Jonathan Benoit on June 11, 2010 at 11:18 AM PDT #

Hey Jon,

are you sure you redeployed the app? I guess you might have missed doing this.

Posted by Naresh on June 11, 2010 at 08:25 PM PDT #

Hi Naresh,
I did redeploy, multiple times. I've tried Clean & Build followed by deploy, that didn't help, still behaved same. This was on Windows. I just tried on Solaris using netbeans-6.8-ml-solaris-sparc.sh and it worked when i entered http://localhost:8080/HelloWorldWebapp/resources/hello?name=Joe so looks like i've either got a platform problem on windows or more likely some environment hiccup. i'll revisit my windows setup and see if i can 'start-over' to get past this behavior. i'll post where i end up for completeness. thanks for the feedback.
Jon

Posted by Jonathan Benoit on June 14, 2010 at 02:27 AM PDT #

Jon,

as you said, probably you might be you are hitting a platform specific issue with one of NetBeans/GlassFish/Jersey. Probably, you need to check with the Jersey user alias.

Posted by Naresh on June 14, 2010 at 03:24 AM PDT #

Following your TOI links, I first did [1]http://blogs.sun.com/naresh/entry/building_restful_web_services_using then i did steps in [2]http://blogs.sun.com/naresh/entry/making_the_uri_dynamic followed by steps in this blog entry that i'm commenting on, namely [3]http://blogs.sun.com/naresh/entry/accessing_query_parameters_using_queryparam

[2] says:
\* Modify the @Path annotation given above the HelloResource class as follows:

@Path("hello/{name}")
public class HelloResource {

[2] works fine. next i move on and test [3]. i'm using project from previous example, namely [1] but it has been modified according to steps in [2] as described above. [3] says to modify method to use :

public String sayHello(@QueryParam("name") String name) {

instead of

public String sayHello(@PathParam ("name") String name) {

so when i access url listed in [3] (http://localhost:8080/HelloWorldWebapp/resources/hello?name=Rama) it won't work, instead i get :

HTTP Status 404 -

type Status report

message

descriptionThe requested resource () is not available.

This happens on Solaris and windows. If I change the @Path annotation for the HelloResource class as follows:

@Path("hello/{name}")
public class HelloResource {

back to:

@Path("hello")
public class HelloResource {

then url used in [3] works. Seems you have to reset project back to initial state as described in [1], before doing steps in [3]. If I do steps in [2] before [3], and I don't revert @Path annotation declaration, then it errors as described. Should you be allowed to change:
@Path("hello")
to:
@Path("hello/{name}")
and use :
public String sayHello(@QueryParam("name") String name) {
with:
http://localhost:8080/HelloWorldWebapp/resources/hello?name=Rama

Posted by Jonathan Benoit on June 16, 2010 at 05:55 AM PDT #

If I use:
@Path("hello")
public class HelloResource {
with
public String sayHello(@PathParam("name") String name) {
and access url
http://localhost:8080/HelloWorldWebapp/resources/hello?name=Jonathan
then i see just:
Hello World!

for method defined as:
@GET
@Produces("text/plain")
public String sayHello(@PathParam("name") String name) {
if (name != null) {
// if the query parameter "name" is there
return "Hello " + name + "!";
}
return "Hello World!";
}

which means name is equal to null.

If I just change sayHello method to use @QueryParam instead of @PathParam as:

public String sayHello(@QueryParam("name") String name) {

and access url
http://localhost:8080/HelloWorldWebapp/resources/hello?name=Jonathan
then I see:
Hello Jonathan!
which mean name is not equal null.

Lastly if i next change
@Path("hello")
public class HelloResource {
to:
@Path("hello/{name}")
public class HelloResource {
and use:
public String sayHello(@QueryParam("name") String name) {
accessed via url:
http://localhost:8080/HelloWorldWebapp/resources/hello?name=Jonathan
i encounter :
HTTP Status 404 -

type Status report

message

descriptionThe requested resource () is not available.

Is this all expected behavior?

Posted by Jonathan Benoit on June 16, 2010 at 07:03 AM PDT #

Jon,

yes the observations that you have made in the two earlier comments are correct.

1. As you mentioned in the previous comment, you would have to reset the project to the state it was in [1] before you can exercise [3], i.e., resent the @Path annotation at the HelloResource class from @Path("hello/{name}") to @Path("hello"). I should have mentioned this in the blog entry, sorry for the inconvenience.

2. As for your previous comment, here's what is happening:

@Path("hello")
public class HelloResource {

public String sayHello(@PathParam("name") String name) { ... }

}

When you access-
http://localhost:8080/HelloWorldWebapp/resources/hello?name=Jonathan you would get "Hello World!" since you are passing the name as query parameter and not as a path parameter, i.e., not as "/hello/Jonathan". Hence the path parameter is evaluated as null, and you get the "Hello World" instead of "Hello Jonathan".

So the mantra is-

if you try to access a variable "name" as path parameter, then you need to set the path as @Path("/hello/{name}"). However, if you want to access it as a query parameter, set it as query parameter in your request URL and change the path to @Path("/hello") and in your resource method fetch it using the @QueryParam annotation.

Posted by Naresh on June 16, 2010 at 02:02 PM PDT #

Hello, I want to know if the name is not ASCII char, how could we get the right string by using @QueryParam. Such like chinese char
http://localhost:8080/HelloWorldWebapp/resources/hello?name=你好
seems @QueryParam could not set the decoding charset.

Posted by kevin_LV on September 15, 2010 at 08:24 PM PDT #

Kevin,

sorry I do not have much information regarding this particular use-case.
Probably, you should post it at the Jersey users mailing list, users@jersey.dev.java.net.
You can most likely get a solution to this problem there.

Posted by Naresh on September 15, 2010 at 10:37 PM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Naresh worked at Sun Microsystems for two years. During these two years he had worked on the Project Metro and Project Jersey.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today