Tuesday, December 9th, 2008

Implementing Ajax in Java web application using JQuery

Implementing Ajax features in a Java web application is considerably easy if we are using JQuery JavaScript library. JQuery provides built-in methods that we can use to enable Ajax in our Java web application.

In this post, I am going to demonstrate the Jquery’s Ajax capability using a small weather reporting web application. Before that, you can have a look at the source code by clicking on below link.

Download Source Code

A Simple weather reporting application:

Lets build a simple Java web application. User will be entering the city name and application will return the weather report for the given city.

For the above requirements, a simple application design would contain a Java servlet to serve the weather report for the city passed as a parameter and a web page for the user to enter a city name and to see the weather report. All the communication between the web browser and Java servlet should happen through Ajax calls. Using JQuery’s post Ajax function, we can asynchronously send data to server.

WeatherServlet.java

package com.veerasundar.weather;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author veerasundar.com/blog
 *
 */
public class WeatherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public WeatherServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String city = request.getParameter("cityName");
		String report = getWeather(city);
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		out.println("" + report + "");
		out.flush();
		out.close();
	}

	private String getWeather(String city) {
		String report;

		if (city.toLowerCase().equals("trivandrum"))
			report = "Currently it is not raining in Trivandrum. Average temperature is 20";
		else if (city.toLowerCase().equals("chennai"))
			report = "It's a rainy season in Chennai now. Better get a umbrella before going out.";
		else if (city.toLowerCase().equals("bangalore"))
			report = "It's mostly cloudy in Bangalore. Good weather for a cricket match.";
		else
			report = "The City you have entered is not present in our system. May be it has been destroyed "
					+ "in last World War or not yet built by the mankind";
		return report;
	}

}

As you see from the above code, the servlet WeatherServlet tries to read the city name from the request and it matches the city name against some pre-defined names and returns the weather report. In an production application the weather will be retrieved from a real time database. As this demo concentrate more on JQuey + Ajax feature, I kept the example as simple as possible.

Web.xml configuration for WeatherServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>weather</display-name>
	<servlet>
		<servlet-name>WeatherServlet</servlet-name>
		<servlet-class>com.veerasundar.weather.WeatherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>WeatherServlet</servlet-name>
		<url-pattern>/WeatherServlet</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Above code snippet defines our WeatherServlet and it’s URL pattern so that when the URL pattern is requested by the client, our servlet will be called.

index.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX and Java - veerasundar.com</title>
</head>
<body>
	<form method="post">
	Enter City :
		<input id="cityName" name="cityName" size="30" type="text" />
		<input id="getWeatherReport" name="getWeatherReport" type="button" value="Get Weather" />
	</form>
	<div id="weatherReport" class="outputTextArea"></div>

	<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
	<script type="text/javascript">
	$(document).ready(function() {
		$("#getWeatherReport").click(function(){
			$cityName = document.getElementById("cityName").value;
			$.post("WeatherServlet", {cityName:$cityName}, function(data) {
				alert(data);
				$("#weatherReport").html(data);
			});
		});
	});
	</script>
</body>
</html>

Above snippet construct the parameter cityName from the entered value and calls our servlet WeatherServlet by passing this cityName. Also a callback function defined which is called when the Ajax request is complete. In our case what it does is gets the value of the “report” string in the server-returned xml data and populates this value to the “weatherReport” HTML DIV section.

Download Source Code

So, what do you think? Have you used JQuery in any of your applications? Feel free to share your thoughts in the comments section.

{ 40 comments… read them below or add one }

Sudhir December 19, 2008 at 12:43 pm

Nicely explained….
Personally I like jquery because of its selectors/event binding/ and dom utilities..

But for ajax and other cool effects I prefere prototype or script.aculo.us

Reply

Sudhir December 19, 2008 at 12:43 pm

Nicely explained….
Personally I like jquery because of its selectors/event binding/ and dom utilities..

But for ajax and other cool effects I prefere prototype or script.aculo.us

Reply

veerasundark December 19, 2008 at 2:24 pm

Thanks Sudhir.

I like JQuery for the same reason you mentioned. But Ihaven't tried other frameworks (prototype etc) as of now. have to experiment them also.

Thanks for your comment.

Reply

Veera December 19, 2008 at 2:24 pm

Thanks Sudhir.

I like JQuery for the same reason you mentioned. But Ihaven't tried other frameworks (prototype etc) as of now. have to experiment them also.

Thanks for your comment.

Reply

learn spring, ajax December 22, 2008 at 3:33 am

Very nice !!! Thank you for sharing.
cheers

Reply

learn spring, ajax December 22, 2008 at 3:33 am

Very nice !!! Thank you for sharing.
cheers

Reply

A very thankful person February 27, 2009 at 11:06 am

Thanks a lot for sharing. I had been searching an example that uses JQuery and servlets for the last two days and everywhere i found Jquery using PHP. You have also explained it very good. This helps a lot.

Thank You very much

Reply

Markus June 24, 2009 at 10:57 pm

Thanks for this short but very good example. Just what I was looking for :)

Reply

Veera June 24, 2009 at 11:09 pm

you are welcome!

Reply

taysay July 24, 2009 at 12:15 pm

This is a wonderful gift to the developer community and the
world at large who get to feel the developers effort. So between jquery and dojo, moo tools (etc) which plugs in better into java application? I am not trying to spark off an argument here.

Reply

Veera July 24, 2009 at 3:34 pm

Hi Taysay,

I’ve not used Moo tools or Dojo, so I can’t comment on them. But, I’ve been using JQuery for a long time with my Java project. I’ve never faced any issues. More over, all these JavaScript frameworks are client side technology. So, it doesn’t affect what technology (PHP/Java/.Net) we are using at server side.

BTW, JBoss MyFaces framework provides an in-built support for JQuery. :)

Reply

Rajeev Sharma September 7, 2009 at 1:43 pm

I have tried this sample code .but when clicking the button the jsp page is not getting submitted.
I have put alerts to debug, so alerts are invoked just before post line : i.e
$.post(“WeatherServlet”, {cityName:$cityName}, function(xml) {

Please tell me why the jsp is not getting submitted.
Waiting for your reply….

Reply

rajeev sharma September 7, 2009 at 2:34 pm

Actually I was trying this in Weblogic Portal.
so there i found this problem.

but in normal webapp it is working fine.
thanks….

Reply

Dhuraikkannu October 9, 2009 at 1:50 pm

I am having one doubt in jquery regarding drag and drop.
http://www.webresourcesdepot.com/dynamic-dragn-drop-with-jquery-and-php/
From this link, I got drag and drop code in PHP. I tried that in Servlet but I am not knowing, how to retrieve array values in Servlet Any suggestions for this?

Reply

rajendra November 24, 2009 at 1:38 am

Hi,
This is Nice!! can we implement Jquery Along with any other technology like JSP/Struts/JSF? if so, can you provide me an example on how to do these.

thanks raj

Reply

Veera November 24, 2009 at 7:19 am

off course, JQuery can be implemented with all the above you said and the implementation method is same as what I explained in this post. In fact, JSF comes with pre-built JQuery support in it. So, in JSF alone, the usage will be little different.

Reply

jorkua November 25, 2009 at 9:33 pm

What is the importance to use the ajaxify plugin (<servlet-class>ajaxify.WeatherServlet</servlet-class>). ???

Actually, I can´t get the response in the web browser, via firebug I know that servlet is returning the hoped data, but it doesn't appear on the web browser.

Reply

Veera November 25, 2009 at 10:50 pm

Hi Jorkua,

If I understood your question correctly, there's no plugin called 'ajaxify' – its the package name for my Java classes.

And as you said you are getting the response from the Servlet and make sure that you have a HTML DIV with an id as 'weatherReport', if you are following the naming conventions as given in the above example. Because JQuery looks for this ID name for updating the server's response.

do let me know if u have any more question. I'm happy to answer those. :)

Reply

jorkua November 26, 2009 at 12:58 am

Yes, i suppossed that..!! (there's a plugin named ajaxify).

The problem was that in the example are missing the xml tags.

You have out.println(“” + report + “”); and must to be out.println(“<WeatherServlet><report>” + report + “</report></WeatherServlet>”);

Can you help me with the “callback fuction parameter”, instead of XML I wanted it in HTML, I have the next code:

JSP (Only the .post function)
—————————————
$.post(“CostoProdPorCuentaServlet”,
{
method:$metodo,
cuenta:$accountant,
nivel:$level
},
function(data) {
$(“#datos1″).html(report.text());
},
“html”);
—————————————

On the servlet, i've changed the response.setContentType(“text/xml”); to response.setContentType(“text/html”); I think that the problem is in the way that i am catching the value in the callbackfuction.

Thanks.. !!

Reply

jorkua November 26, 2009 at 5:07 am

I resolved it…

$.post(“CostoProdPorCuentaServlet”, {method:$metodo,cuenta:$accountant,nivel:$level}, function(data) {
$(“#datos1″).html(data);
},”html”);

thanks..!!

Reply

Veera November 26, 2009 at 5:27 pm

great!

Reply

Naveen November 10, 2010 at 4:31 pm

I found this interesting artilce at IBM developerWorks about optimizing jQuery + Java.

http://www.ibm.com/developerworks/java/library/wa-aj-zkquery/

Reply

Veera November 11, 2010 at 4:33 pm

looks good.

Reply

Roben May 3, 2011 at 2:48 pm

Can we call JAX-WS using AJAX? Or do we need a servlet in between to serve the request ad response ?

Reply

Veera May 3, 2011 at 3:31 pm

yes you can, provided that the web services running in the same domain as of the AJAX script. Because, you can not do a cross-domain request in AJAX due to security risks.

Reply

Joseph Chackochen May 25, 2011 at 7:48 pm

I was able to use this technique to query database and update the page.
Thank you very much for the posting.

Is it possible to publish this article using JSON from servlet and show how to format on a browser page.

Joseph

Reply

Veera May 26, 2011 at 3:28 pm

Let me work on the example and will publish.

Reply

Pedro José June 1, 2011 at 11:57 pm

Hi, Veera
Just correcting on line 21 you are forgot to use JQuery.

Line 21: $cityName = document.getElementById(“cityName”).value;

Correction:
$cityName = $(‘#cityName’).value;

That’s it.
Congratulations for your post! I really like it!

Reply

pekos October 11, 2011 at 6:37 pm

in the latest jQuery version this doesn’t work… you get undefined for alert($cityName);
It should be
$cityName = $(“#cityName”).val();

This is how i made it to work, a small correction there. Nice observation though.

Reply

Ravi June 7, 2011 at 9:32 pm

Hi Veera,

Very helpful post. You have made it very easy to understand the concepts.

Keep up the good work.

Thanks,

Reply

Raj July 27, 2011 at 11:59 pm

Nice one…
Thanks…
I liked it very much… :)

Reply

sathish September 3, 2011 at 12:22 pm

Thanks very much I was in confusion as Jquery was not running for me .
After I tried ur example it was damn clear.
Thanks a lot once again .

Reply

Ramu January 4, 2012 at 11:58 pm

I have question regarding Jquery and spring, how to make a post call onchange from jsp to controller by using jquery ??

Thanks

Reply

vijay March 8, 2012 at 8:45 am

Hi I am looking for setting the log4j.xml log levels dynamically…. please help me out..

Reply

Veera March 8, 2012 at 12:42 pm

can you elaborate about your requirement?

Reply

Swarnajith March 31, 2012 at 12:54 pm

Hi,
I like to know whether you know a way to do a jquery AJAX poll in a JSF facelets web application(without any custom faces libraries such as prime/rich/ice).
Basically I want to get server updated data to web front-end which is .xhtml file and consists of jsf tags and HTML tags.

Thanks in advance.

Reply

fer April 23, 2012 at 2:24 pm

great example!! it has been very useful for me!

Reply

Sandra May 1, 2012 at 9:20 pm

Thanks! This is just what I was looking for :)

Reply

maheshbabu nadilla May 10, 2012 at 9:53 am

nice veera sundar garu nice explanation

Reply

maheshbabu nadilla May 10, 2012 at 9:56 am

i am trying last two days but i can’t get it.once i saw your example i got an idea on ajax and jquery thank you thank you very much.keep going…………..

Reply

Leave a Comment

{ 4 trackbacks }

Previous post:

Next post: