Thursday, August 15, 2013

JAX-RS access via JSON using jQuery

This is the continuation of the blog  JSF 2.0 Ajax.
In the blog JSF 2.0 Ajax, I’ve considered the Ajax access using JSF 2.0. In JSF, you have to always use the Managed bean. As I see managed bean is over managed therefor more code need to be added to avoid the unnecessary side effects such as save twice. The REST approach is simple but unsecure.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</h:head>
<body>
    <form action="/eafirstweb/rest/dept" id="deptForm">
        Department:
        <input type="text" name="dept_Name"/>
        <input type="submit" value="Add"/>
    </form>
    <span id="msg"></span>
    <script type="text/javascript">
        $("#deptForm").submit(function(event){
            //stop from submitting normal way
            event.preventDefault();
            
            var $form = $(this);
            //var deptName = $form.find('input[name="dept_Name"]').val();
            var url = $form.attr('action');
            
            //send the data using POST
            /*var posting = $.post(url, deptName).done(function(data){
                alert(data);
            });*/
            $.ajax({
                type : 'POST',
                url : url,
                data : $form.serialize(),
                success : function(data){
                    var table ='<table><tr><th>Dept Id</th><th>Dept Name</th></tr>';
                    $.each(data, function(index, item){
                        table += '<tr><td>'+item.deptId+'</td><td>'+item.name+'</td></tr>';
                    });
                    table += '</table>';
                    $('#msg').html(table)
                }
            });
            
        });
    </script>
    
</body>
</html>
In the above code, form data is serialized and send to the url where the REST service is available. The following code shows the services which are written in JAX-RS
package au.com.blogspot.ojitha.eafirstweb.rest;

import java.util.List;

import javax.ejb.EJB;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import au.com.blogspot.ojitha.eafirstejb.DepartmentService;
import au.com.blogspot.ojitha.eafirstejb.domain.Department;

@Path("dept")
public class DeptRestService {
    
    @EJB(beanName="deptService")
    DepartmentService deptService;
    
    @SuppressWarnings("unused")
    @Context
    private UriInfo context;

    /**
     * Default constructor. 
     */
    public DeptRestService() {
        
    }

    /**
     * PUT method for updating or creating an instance of Hello
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/html")
    public void putHtml(String content) {

    }
    
    @GET
    @Path("{deptId}")
    @Produces("application/json")
    public Department getDepartment(@PathParam("deptId") Long deptId){
        Department dept =this.deptService.findDepartmentById(deptId);
        return dept;
    }
    @Produces("application/json")
    @GET
    public List<Department> getAllDepartements(){
        return this.deptService.getAllDepartments();
    }
    @POST
    @Consumes("application/x-www-form-urlencoded")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Department> addDept( @FormParam("dept_Name") String deptName){
        this.deptService.save(deptName);
        return this.deptService.getAllDepartments();
    }

}
As shown in the above code, the target method is addDept. In that method, form parameter “dept_Name” is extracted using @FormParam annotation process. In the next line save the new department. As a return, send back all the available department as a JSON type back to the page. In the page, in the success function, these data being written in to the table.

Above picture shows the resulting web page with Firebug xhr requests and response.
The source code of this blog is available in the GitHub.