Search code examples
javajsonjpajakarta-eeejb

How to expose the business logic as a RESTful web service to be consumed by a mobile application?


I am working on the server side of a mobile application. One of the requirements I have is to implement the server using Java EE, JPA, EJB, and JSON.

I am new to Java EE but I did some reading and so far managed to build the business logic by implementing the Pojos and the EJBs of the project.

Where I am encountering difficulties is in figuring out how to expose my EJBs as a RESTful web service that can be consumed by the client side of the application. I could find some documentation and tutorials but all of it was related to building a backend for a website as opposed to mobile.

What are the best practices in exposing the business logic as a RESTful web service to a mobile application in a Java EE environment?


Solution

  • I'm not sure what your app server is but with JavaEE 6 and 7, you can do this fairly easily. Take a look at this tutorial for a good starting point. In general, a simple service would look something like:

    @Path("/login")
    public class LoginService  {    
    
        @Consumes({MediaType.APPLICATION_JSON})
        @Produces({MediaType.APPLICATION_JSON})
        @POST
        public Response login(LoginRequest loginRequest) throws Exception {  
        // your code
        }
    

    where LoginRequest in this case is simple Java POJO that has an equivalent in the JavaScript world.

    Note that it doesn't matter what the client side is - the server just wants the JSON encoded object to come in and it can be a browser or a native mobile app.

    A bit of an issue is how to initialize your app servers underlying Rest framework. Some use web.xml, some use a specially annotated class. That is a bit of a different question - let us know which app server you're using.