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.
- Implementing Ajax in Java web application using JQuery
- Implementing a Web Application Firewall using ModSecurity
- using mysql in java application
- using Camel in a Web Application
- Introduction to using Java Persistence API in a web application in Java EE environment
- Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net
- Implementing Callback Functions Using Delegates In C++
- Implementing Pooling in Application Module Code
- Implementing Sugarcrm: A Step-by-step Guide to Using This Powerful Open Source Application in Your B
- Using the Web Service Callbacks in the .NET Application
- Creating a Simple Web Application in NetBeans Using MySQL(1)
- Simple Web Application using Cherrypy in Python 3.3 with MySQL
- Using Couchbase Server In A GoLang Web Application
- Ajax in Struts: implementing dependent select boxes
- File Upload using jQuery AJAX in ASP.NET Web API or Http handler (AJAX上传文件通过Web API或 http handler)
- Implementing download manager in web view.
- Using $.ajaxPrefilter() To Configure AJAX Requests In jQuery 1.5
- Using Java Web Start in NetBeans IDE
- 走迷宫//迷宫地图在数据文件maze.in中
- layoutSubviews何时调用的问题
- windowxp 安装 redmine1.41
- 最小生成树模板(Prim+优先队列)
- 厨房小白的福音: 菜谱应用横向评测
- Implementing Ajax in Java web application using JQuery
- Android Service---给用户发送通知
- 我的学厨记——香煎鸡翅
- Android模拟机访问本机时的ip地址设置问题
- Android Service---在前台运行服务
- PostgreSQL触发器2
- MFC UI界面自绘制
- Android Service---管理服务的生命周期
- 一、 享元(Flyweight)模式