RESTEasy Javascript/Ajax Client Demo

RESTEasy provides a very excellent support for building Ajax powered clients if you are developing web application. RESTEasy can generate a JavaScript API that uses AJAX calls to invoke JAX-RS operations. The JavaScript code generated for accessing REST APIs looks becomes very similar to java code and you will feel you are calling the REST APIs in java language.

The beauty (or drawback?) of this approach is that your class names and method names are directly accessible through javascript code. Even you do not need to write the Ajax handling code, that is automatically embedded in your webpage.

Note: Using class and method names in JS code might become a very serious security loop hole. So please use it wisely.

In this tutorial, I have built a normal HTML form which is user to add a user into the system. I will use RESTEasy Ajax client for accessing the REST API for adding the user and getting the response back.

Step 1) Add the runtime support for RESTEasy JSAPI

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jsapi</artifactId>
	<version>2.3.1.GA</version>
</dependency>

You can add the jar files in your lib folder if you are not using maven build tool.

Step 2) Add JSAPI servlet mapping

Add below servlet declaration in your web.xml file. The JavaScript API servlet must be configured to enable the JavaScript API.

<servlet>
	<servlet-name>RESTEasy-JSAPI</servlet-name>
	<servlet-class>org.jboss.resteasy.jsapi.JSAPIServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>RESTEasy-JSAPI</servlet-name>
	<url-pattern>/js/*</url-pattern>
</servlet-mapping>

Step 3) Write REST API which needs to be called from javascript/ajax

I am writing a minimal REST API for not making the example complex.

@Path("/rest")
public class UserService 
{
	@Path("/users")
	@POST
	public Response addUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName)
	{
		//vaildate first name
		if(firstName == null || firstName.isEmpty())
		{
			return Response.ok().entity("First name is mandatory dude").build();
		}
		//vaildate last name
		if(lastName == null || lastName.isEmpty())
		{
			return Response.ok().entity("Don't you have any last name? I will keep secret").build();
		}
		//Add user and return the response
		return Response.ok().entity("User "" + firstName + "" added through JAX-RS JavaScript API").build();
	}
}

Step 4) Build the Ajax client at view layer

I am using the default index.jsp file for writing the client code.

Example 1:

<html>
	<head>
		<!-- This will include the whole javascript file including ajax handling  -->
		<script lang="javascript" src="./js"></script>
		
		<!-- Write the javascript code for accessing REST APIs -->
		<script lang="javascript">
			function addUserForm()
			{
				//Collect input from html page
				var firstNameTxt = document.getElementById("firstName").value;
				var lastNameTxt = document.getElementById("lastName").value;
				
				//Call the REST APIs with directly method names
				var message = UserService.addUser({firstName:firstNameTxt,lastName:lastNameTxt});
				
				//Use the REST API response
				document.getElementById("error").innerHTML = "<h2><span style='color:red'>" + message + " !!</span></h2>";
			}
		</script>
	</head>
	<body>
		<h1>RESTEasy Ajax client demo</h1>
		<div id="error"></div>
		<form method="post">
			<p>First Name : <input type="text" name="firstName" id="firstName"/></p>
			<p>LastName : <input type="text" name="lastName" id="lastName"/></p>
			<input type="button" value="Add User" onclick="addUserForm()" />
		</form>
		Demo by : <b>http://www.howtodoinjava.com</b>
	</body>
</html>

Example 2:

If you find using class names and method names not manageable because they might get change on another day. Do not worry, REST implicit object is to rescue you. A demo REST call be made like this:

//Example Two using REST object
function addUserForm()
{
	//Collect input from html page
	var firstNameTxt = document.getElementById("firstName").value;
	var lastNameTxt = document.getElementById("lastName").value;
	
	var req = new REST.Request();
	req.setURI(REST.apiURL + "/rest/users");
	req.setMethod("POST");
	req.setEntity({firstName:firstNameTxt,lastName:lastNameTxt});
	req.execute(function(status, request, entity){
		document.getElementById("error").innerHTML = "<h2><span style='color:red'>" + entity + " !!</span></h2>";
	});
} 

Test the application

To test the application, deploy the application in any web server.

1) Type the URL http://localhost:8080/RESTfulValidation/

resteasy-ajax-demo
Demo welcome screen

2) Fill Only First Name and press add button

Validation error for last name field
Validation error for last name field

3) Fill Both fields and press add button

User added successfully
User added successfully

To download the source code above demo, follow below given download link.

Sourcecode Download

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “RESTEasy Javascript/Ajax Client Demo”

  1. Uncaught ReferenceError: UserService is not defined index.jsp:14
    addUserForm index.jsp:14
    onclick

    i am new to this also i am using apache tomcat server .
    can you please help me.

    Reply
  2. Lokesh – Thanks.. I could finally make your example 2 JSP segment work. For anyone else trying to do it, that segment requires user.java, jackson provider as well as additional method in userservice.java to handle JSON object posted by example 2.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.