RESTful Web services on JBoss AS 7

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive

In this sample tutorial we will show how to run RESTful Web services on JBoss AS 7 (release 7.0.2) using CDI and JPA to load persistent data.

In order to use Web services in the new application server release you need the following extension in your configuration file:

<extension module=""/>					

This extension is included by default since JBoss AS 7.1.1. In this example we will build a sample application which uses a RESTful Web services to gather some data which is returned in XML format. The first piece of our application will be the RESTful Web service which produces a list of Entities (of type Book):

package com.webservice;

import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import javax.persistence.Query;

public class RESTService  {
private EntityManager em;    
 public List<Book> listUsers() {
   Query query = em.createQuery("FROM com.entity.Book");
   List <Book> list =  query.getResultList();

   return list;

In this example, we are binding the Path to the specific context named "/list".
You can apply the @Path annotation also at method level so that you can specify different virtual paths for your web services.

Now Let's add the Entity class named Book to our project, which simply maps the table named "Book" on the database:

package com.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;

public class Book {

 @Column(name = "name")
 String name;
 @Column(name = "isbn")
 String isbn;
 @Column(name = "price")
 int price;

public Book() {   }

public String getName() {
   return name;

public void setName(String name) { = name;

public String getIsbn() {
   return isbn;

public void setIsbn(String isbn) {
   this.isbn = isbn;

public int getPrice() {
   return price;

public void setPrice(int price) {
   this.price = price;


Next thing, as we have seen, this project uses Context Dependency Injection to inject the EntityManager into our project. In order to do that, we need a simple qualifier which exposes an entity manager using the resource producer pattern :

package com.qualifier;

import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class Resources {

 private EntityManager em;


After that, in order to activate CDI, you need to place the beans.xml file into the WEB-INF folder of your application, so that the deployer triggers CDI deployment. As we are not defining any beans into this file, just place add an empty file named beans.xml under WEB-INF.