Purpose of jersey-server, jersey-client, jersey-grizzly in RESTful application
Asked Answered
S

1

5

I am trying to create a basic RESTful application using Maven,Apache Tomcat 7.0, Eclipse IDE. I came across the usage of maven dependencies like jersey-server, jersey-client, jersey-grizzly etc in some of the sample codes available in google.

I wanted to know the purpose of these dependencies ie. why we add them,what it does, how they work?

I have referred several jersey javadocs but am unable to get a clear picture. Please provide a simple explanation for the same.

Thanks in advance

Selfness answered 19/1, 2014 at 6:6 Comment(0)
M
8

In a nutshell: you use jersey-server to expose REST APIs like in this example:

@Path("/hello")
class RESTDispatcher {

    @GET
    @Path("/world")
    public String helloWorld() {
        return "Hello world!"
    }
}

You use jersey-client to consume REST APIs

public static String callRestAPI(String[] args) {
    Invocation.Builder builder = ClientBuilder
                                .newClient()
                                .target("http://localhost/hello/world");
    Response response = builder.method("GET");
    String result = response.readEntity(String.class);
    return result; 
    //will return "Hello world!" with our previous example deployed on localhost
}

And jersey-grizzly just to use jersey with grizzly server.

UPDATE
I meant that we need jersey-client every time when we need to call REST API exposed by someone.
My example of jersey-client usage assumes that first example deployed on your localhost. See annotations of first example, @Path of class and @Path of method results in path /hello/world, that should be called with HTTP GET request (see @GET annotation).
So we create REST client with that target

Invocation.Builder builder = ClientBuilder
                            .newClient()
                            .target("http://localhost/hello/world");

then we call this target with HTTP GET request

Response response = builder.method("GET");

Then we know (from signature of helloWorld method) that this API response contains an entity that could be deserialized into instance of String. So we read it into "result" variable

String result = response.readEntity(String.class);

You should provide target class of deserialization as parameter to readEntity method of response.
Also, it's not common for REST API to return just String. Rather, they return JSON or XML. In that case you could use JAXB to read entity, Jersey works perfectly with it. Check this part of documentation for XML support and this for JSON.

Mezzosoprano answered 20/1, 2014 at 7:53 Comment(1)
Thank you for your reply.....It would be helpful if you could elaborate on jersey-client "consumes" rest APIs.Selfness

© 2022 - 2024 — McMap. All rights reserved.