Tutorial: Creating RESTful Web Services with EJB 3.1

RESTful web services has gained a lot of acceptance across the web, they are basically web services that follows the REST guidelines. In this short tutorial I’m going to create a very simple Hello World application that implements a RESTful Web Service using EJB 3.1.

I’m assuming that you already have your environment setup and also a Java EE project created and ready to use.
So let’s get started, the first step is to create a session bean that looks like this:

1
2
3
4
5
6
7
8
9
10
@Stateless
@Path("/sayHello")
public class HelloWorld {
 
   @GET
   @Produces("text/plain")
   public String sayHello() {
       return "Hello World!!";
   }
}

That’s really a straightforward implementation, we’ve used the annotation @Path to specify the URI path we’re going to use to access this service, we also created an operation accessible via HTTP GET (indicated by the @GET annotation), and lastly we specified the media type that this operation will produce, in this case it’s a plain text, but it could also be a JSON, XML, etc.
After creating the session bean, the second and last step is to register the servlet adaptor in the web.xml:

1
2
3
4
5
<servlet>        
     <servlet-name>ServletAdaptor</servlet-name>        
     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>        
     <load-on-startup>1</load-on-startup>    
</servlet>

That’s it! You have already created a RESTful Web Service!!
Now if you deploy you project, you can go to your browser and type http://{projectURL}/sayHello, you’ll see the string “Hello World!!” displayed on the page.

Hope this post was helpful for you,
Till next Time!

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>