2.10. Add a RESTful Web Service
For the TicketMonster application to be able to access the information stored in the database, web services are needed. The procedure below creates a RESTful web service that returns all the events in the database. It generates a POJO (plain old Java object) and adds JAX-RS annotations to create an endpoint.
Procedure 2.10. Add a RESTful Web Service
- In the Project Explorer view, expand ticket-monster→Java Resources→src/main/java.
- Right-click org.jboss.jdf.example.ticketmonster.rest and click → .
- In the Name field, type
EventService
and click . This creates aEventService.java
file that is automatically opened in a Java editor.Figure 2.18. Completed Name Field in Java Class Wizard
- Add the following lines immediately above
public class EventService {
@Path("/events") @RequestScoped
and add the following lines in between the braces of the EventService class@Inject private EntityManager em; @GET @Produces(MediaType.APPLICATION_JSON) public List<Event> getAllEvents() { final List<Event> results = em.createQuery("select e from Event e order by e.name").getResultList(); return results; }
- Save the
EventService.java
file. - Resolve the errors relating to missing imports by right-clicking anywhere in the
EventService
class and clicking → . - For each class name that is not unique, select the class to use as follows and click:
- For
MediaType
select javax.ws.rs.core.MediaType - For
Event
select org.jboss.jdf.example.ticketmonster.model.Event - For
Produces
select javax.ws.rs.Produces - For
List
select java.util.List - For
Inject
select java.inject.Inject - For
RequestScoped
select java.enterprise.context.RequestScoped
Figure 2.19. javax.ws.rs.core.MediaType Selected for
MediaType
Class - When all the classes have been chosen, click. The import statements corresponding to the class names selected in the previous step are added to the
EventService.java
file. - Save the
EventService.java
file. - In the Servers view expand jboss-eap-6.x, right-click ticket-monster and click to update the deployed version of the application.
- Open a new Web Browser and in the address bar of the Web Browser enter http://localhost:8080/ticket-monster/rest/events. This shows the output of the new RESTful endpoint.