JAXRS with jQuery and ajax

 

                            NOTE: Source Code available for download at the bottom of the page

 
What are we Going to do?
    We will build a small web application where users can be added and searched using REST calls generated through Ajax using jQuery. For the ease of development, we will have a static list which will hold our users.
 
What will be the end output look like ?
 
Home Page
 
 
What do you need ?
  • Maven
  • JDK 1.5 or higher
  • eclipse 
  • Jersey - We will be using Jersey implementation in our example
  • jQuery for Ajax calls.
  • Tomcat
How are we going to do ?
 
Step 1:
   Create a dynamic web project as shown here.
 
Step 2:
     In order to use Jersey implementation for JAX-RS, we will need necessary jars to be downloaded. Add the following         dependencies to your pom file and do Maven -> Update Project to get proper references to the jars.
 
pom.xml
											 <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.8</version>
    </dependency>
 
Step 3:
 
     Our web application has to know how the REST URI's have to be processed. So lets come to an agreement that             JAX-RS calls in our application will follow the following pattern
             http://localhost:8080/JAXRS-Example/rest/.....
 
     We will add the Servlet mapping to forward /rest/* calls to jersey implementation as shown below. In order for         the incoming requests to reach our classes, we will have to register our package with Jersey implementation.
     This is done by adding the following.
 
											                <init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>com.visionjava.restservices</param-value>
		</init-param>
 
web.xml
										<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>Archetype Created Web Application</display-name>
	<servlet>
		<servlet-name>rest-servlet</servlet-name>
		<servlet-class>
			com.sun.jersey.spi.container.servlet.ServletContainer
		</servlet-class>
		<init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>com.visionjava.restservices</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>rest-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>
 
 
Step 4:
    We will create 2 methods to handle the HTTP POST for adding a user and HTTP GET for returning list of users.
    
										package com.visionjava.restservices;

import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.visionjava.model.User;

@Path("/user")
public class UserProcessor {
	
	private static List<User> users = new ArrayList<User>();
	@POST
	@Path("/add")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.TEXT_HTML)
	public Response addUser(User us) {
		users.add( us );
		return Response.status(200).entity("Successfully added user " + us.getName()).build();
	}
	
	@GET
	@Path("/search")
	@Produces(MediaType.APPLICATION_JSON)
	public List<User> getUser(@PathParam("userId") String id){
		return users;
	}
}

    Now let's analyze our class. 
        @Path("/user") designates our class to handle all the uri's with pattern /user/*
										        @POST designates add User method to handle HTTP POST methods
	@Path("/add") further narrows the URI that will be handled by addUser to /rest/user/add
	@Consumes(MediaType.APPLICATION_JSON) indicates that that input expected by this method is JSON type object
	@Produces(MediaType.TEXT_HTML) indicates that the output or return values of this method is text/html
										
										   You might be wondering that we have indicated the input Consumes to be of type JSON but our method signature addUser     takes parameter of type User. This automatic conversion is done by jersey-json library we have added in our pom file     earlier.
										
										                                        <dependency>
                                            <groupId>com.sun.jersey</groupId>
                                            <artifactId>jersey-json</artifactId>
                                            <version>1.8</version>
                                        </dependency>
										
										    Same thing applies to the getUser method which produces JSON response. 
										
										
										index.jsp
											
											<html>
<script
	src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
	
</script>


<script>
	$(document).ready(
	function() {
		$("#search").click(
				function() {
					$.ajax({
						url : "rest/user/search",
						success : function(result) {
							$('#searchResultdiv').html('');
							$.each(result, function(index, user) {
								$('#searchResultdiv').append(
										'<li>  --> <b>Name :</b> '
												+ user.name
												+ ', <b>Age :</b>'
												+ user.age
												+ ',<b> Password :</b>'
												+ user.country
												+ ', <b>Zip :</b>'
												+ user.zip + '</li>');

							});
						}
					});
				});
				$(".numericOnly").keypress(function(e) {
					if (String.fromCharCode(e.keyCode).match(/[^0-9]/g))
						return false;
				});

				$("#userForm").submit(function() {
					name = $(this).find("#name").val();
					age = $(this).find("#age").val();
					country = $(this).find("#country").val();
					zip = $(this).find("#zip").val();
					var arr = {
						"name" : name,
						"age" : age,
						"country" : country,
						"zip" : zip
					};
					$.ajax({
						type : 'post',
						url : 'rest/user/add',
						contentType : 'application/json',
						data : JSON.stringify(arr),
						success : function(result) {
							$('#addResultDiv').html('');
							$('#addResultDiv').html(result);

						},
						failure : function(result) {
							$('#addResultDiv').html('');
							$('#addResultDiv').html(result);

						}
					});
					return false;
				});

			});
</script>
<body>
	<div id="addResultDiv" style="color: red"></div>
	<h2>Add User!</h2>

	<form id="userForm">
		<table>
			<tr>
				<td>Name :</td>
				<td><input type="text" name="name" id="name" /></td>
			</tr>
			<tr>
				<td>Age :</td>
				<td><input type="text" name="age" id="age" /></td>
			</tr>
			<tr>
				<td>Country :</td>
				<td><input type="text" name="country" id="country" /></td>
			</tr>
			<tr>
				<td>Zip :</td>
				<td><input type="text" name="zip" id="zip" class="numericOnly" />
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="Add User Through REST" /></td>
				<td><input type="button" value="Search Users" id="search" /></td>
			</tr>
		</table>
	</form>
	<div id="searchResultdiv">Search Result will Appear here!</div>


</body>
</html>
 
 
Add User
 
 
 
Search User
 
That's It !!!
Source Code : JAXRS-jQuery-Ajax-Example.rar
Web Analytics