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.
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.
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 }
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
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
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.
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.
Very nice !!! Thank you for sharing.
cheers
Very nice !!! Thank you for sharing.
cheers
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
Thanks for this short but very good example. Just what I was looking for
you are welcome!
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.
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.
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….
Actually I was trying this in Weblogic Portal.
so there i found this problem.
but in normal webapp it is working fine.
thanks….
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?
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
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.
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.
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.
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.. !!
I resolved it…
$.post(“CostoProdPorCuentaServlet”, {method:$metodo,cuenta:$accountant,nivel:$level}, function(data) {
$(“#datos1″).html(data);
},”html”);
thanks..!!
great!
I found this interesting artilce at IBM developerWorks about optimizing jQuery + Java.
http://www.ibm.com/developerworks/java/library/wa-aj-zkquery/
looks good.
Can we call JAX-WS using AJAX? Or do we need a servlet in between to serve the request ad response ?
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.
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
Let me work on the example and will publish.
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!
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.
Hi Veera,
Very helpful post. You have made it very easy to understand the concepts.
Keep up the good work.
Thanks,
Nice one…
Thanks…
I liked it very much…
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 .
I have question regarding Jquery and spring, how to make a post call onchange from jsp to controller by using jquery ??
Thanks
Hi I am looking for setting the log4j.xml log levels dynamically…. please help me out..
can you elaborate about your requirement?
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.
great example!! it has been very useful for me!
Thanks! This is just what I was looking for
nice veera sundar garu nice explanation
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…………..
{ 4 trackbacks }