Developing a REST application using Jersey and running it on AWS Beanstalk

I have had the chance to develop some REST applications at work using Spring in the past and now I would like to try out Jersey to develop a simple REST application which only supports GET operation.

This is not a step-by-step tutorial but rather a place to share what I have.

You can check out the code from Bitbucket.

1. web.xml

The important thing to remember is to specify which package that contains REST resources, as shown in the highlighted lines.

    <servlet>
        <servlet-name>JerseyRest</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.test.resource</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JerseyRest</servlet-name>
        <url-pattern>/rs/*</url-pattern>
    </servlet-mapping>

2. Define REST resource

    @GET
    @Path("/time")
    @Produces({ MediaType.APPLICATION_JSON })
	public Response whatTimeIsIt() {
    	LOGGER.debug("whatTimeIsIt is called");
    	
    	try {
    		String time = (new Date()).toString();    		
    		return Response.ok(time).build();
    	} catch (Exception e) {
    		LOGGER.error("exception occurred", e);
    		return Response.serverError().entity("internal service error").build();
    	}
    }

Method “whatTimeIsIt” is annotated with:

  • @GET – to accept HTTP GET
  • @Path – to specify URL of the resource
  • @Produces – to specify the response header
  • 3. Deploy to AWS Beanstalk

    Creating an AWS Beanstalk environment is pretty straight forward. During the setup, you will have the chance to specify which application to deploy. I chose “64bit Amazon Linux running Tomcat 6”.

    beanstalk.console

    After environment is ready, we can verify that application is up and running by accessing the index page.

    beanstalk.index

    Then, we are ready to access the resource (“time”).

    beanstalk.time

    Ideally, an operation which returns current time is not really a resource as current time is always changing.

    Advertisements
    Developing a REST application using Jersey and running it on AWS Beanstalk

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s