Implementing Ajax in Java web application using JQuery

by Veerasundar on December 9, 2008

in Java, Web

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. I’m not going to give the entire source code here. Instead I am going to explain the important pieces of the application.

A Simple weather reporting application:

Application Requirements:

Build a web application for getting the weather report for any city. The city name should be get from the user as input.

Application Design:

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

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

	String city = request.getParameter("cityName");
	String report = getWeather(city);
	response.setContentType("text/xml");
	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

<servlet>
	<description>Weather Data provider</description>
	<display-name>Weather Data provider</display-name>  

	<servlet-name>WeatherServlet</servlet-name>
	<servlet-class>ajaxify.WeatherServlet</servlet-class>
</servlet>  

<servlet-mapping>
	<servlet-name>WeatherServlet</servlet-name>
	<url-pattern>/WeatherServlet</url-pattern>
</servlet-mapping>

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.

JSP Page to get input from user:

<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>

Above snippet contains a form where user can enter the city name and a DIV section to show the weather report retrieved from the server. This snippet is part of a JSP file.

JQuery to send data thru Ajax

Now comes the imprtant section. JQuery code to send and recieve information to server asynchronously. Have a look the below code.

<script type="text/javascript">
	$(document).ready(function() {
		$("#getWeatherReport").click(function(){
			$cityName = document.getElementById("cityName").value;
			$.post("WeatherServlet", {cityName:$cityName}, function(xml) {
				$("#weatherReport").html( $("report", xml).text() );
			});
		});
	});
</script>

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.

Combine all the above and you are done

If you combine all the above code snippets into a web application, then you are almost done. Now create a WAR out of the web application and deploy it in a web server. After this, invoke the JSP page then enter the city name and click ‘Get Weather’ button which will sends the city name asynchronously to Server using JQuery and will recieve the result and populates the report in an HTML page. All this achieved easily with the JQuery 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.

Follow me on Twitter to get notified whenever I update this blog.

{ 1 trackback }

Dreamz » Blog Archive » Protecting the blog content from being copied
April 16, 2009 at 10:01 PM

{ 21 comments }

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

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

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.

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.

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

Very nice !!! Thank you for sharing.
cheers

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

Very nice !!! Thank you for sharing.
cheers

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

Markus June 24, 2009 at 10:57 PM

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

Veera June 24, 2009 at 11:09 PM

you are welcome!

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.

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. :)

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….

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….

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?

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

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.

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.

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. :)

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.. !!

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..!!

Veera November 26, 2009 at 5:27 PM

great!

Comments on this entry are closed.

Previous post:

Next post: