Implementing Ajax in Java web application using JQuery

来源:互联网 发布:轴承数据 编辑:程序博客网 时间:2024/04/28 19:42

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’spost 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.";elsereport = "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.


原创粉丝点击