HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / RESTEasy / RESTEasy Javascript/Ajax Client Demo

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?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Malini

    November 27, 2014

    var message = UserService.addUser({firstName:firstNameTxt,lastName:lastNameTxt});

    How can I make a call like this if I hv a URL

  2. vinaykumar

    June 14, 2014

    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.

  3. goyaldD

    December 6, 2013

    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.

Comments are closed on this article!

Search Tutorials

RESTEasy Tutorial

  • JAX-RS – Introduction
  • RESTEasy – JBoss
  • RESTEasy – Tomcat
  • RESTEasy – @Path
  • RESTEasy – HATEOAS
  • RESTEasy – SLF4J
  • RESTEasy – Log4j
  • RESTEasy – Download
  • RESTEasy – Upload (MultipartForm)
  • RESTEasy – Upload (HTTPClient)
  • RESTEasy – Custom Validation
  • RESTEasy – Hibernate Validator
  • RESTEasy – ContainerRequestFilter
  • RESTEasy – PreProcessorInterceptor
  • RESTEasy – JAXB XML
  • RESTEasy – Jettison JSON
  • RESTEasy – Jackson JSON
  • RESTEasy – ExceptionMapper

RESTEasy Client APIs

  • RESTEasy – java.net
  • RESTEasy – JAX-RS Client
  • RESTEasy – Apache HttpClient
  • RESTEasy – JavaScript API
  • RESTEasy – ResteasyClientBuilder

RESTEasy Best Practices

  • RESTEasy – Sharing Context Data
  • RESTEasy – Exception Handling
  • RESTEasy – ETag Cache control
  • RESTEasy – GZIP Compression
  • RESTful vs. SOAP

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)