RESTful WS using Jersey Part 2 – Parameterized approach

This post is in sequel  RESTful WS using Jersey Part 1 - Hello World. It shows how to utilize parameterized urls as well as query string. Please refer Part 1 to know developing restful services from scratch. This post utilizes same example.

Parameters can be passed as part of path as well as url query string. Jersey provides two annotations @PathParam  and @QueryParam for extracting parameters from path and query respectively.

We have modified getText method to accept both kind of parameters as below

1. Complete resource class will be

package demo.resorces;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

/**
* REST Web Service
*
* @author Yogesh
*/

@Path("hello/{UserName}")
public class HelloResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of HelloResource */
    public HelloResource() {
    }

    /**
     * Retrieves representation of an instance of demo.resorces.HelloResource
     * @return an instance of java.lang.String
     */
    @GET
    //@Produces("text/plain")
    @Produces("text/html")
    public String getText(@PathParam("UserName")  String userName,
               @QueryParam("query") String query
) {
        //TODO return proper representation object
        //return "Hello from GetText";
        String response = null;
        if("location".equalsIgnoreCase(query))
            response = "<html><body><h1>"+userName+"'s location is Hyderabad</h1></body></html>";
        else if ("age".equalsIgnoreCase(query))
            response = "<html><body><h1>"+userName+"'s age is 26</h1></body></html>";
        return response;
    }

    /**
     * PUT method for updating or creating an instance of HelloResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/plain")
    public void putText(String content) {
    }
}

Here two main changes are

  • Modified @path annotation so that it recognize path parameters "hello/{UserName}", whatever will after after hello/ will be considered as value for USerName parameter.
  • getText method accep parameters with thwo annotations @PathParama and @QueryParam. Both are being used to parse respective parameters from url to parameters.

2. Modify Project property to change default launch url to include parameters in url

11

3. Run the project and you will see following output

12

Change the query parameters as ?query=location

13

Comments

Post a Comment

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example