Sunday, May 27, 2012

jQuery Tutorial: Ajax Processing - GET and POST

Overview:
This article will be on jQuery. jQuery simplifies the manipulation of DOM elements. Here, we'll be mainly focusing on how jQuery eases the usage of the Ajax API.

The sample code can be found here.

Application Demo:
The application is to add and display weather information about cities.

Home page:

Select City:



Display Selected City:


Adding a New City:



Submitting the New:


Project Structure:
 org.fazlan.jquery.app  
 |-- pom.xml  
 `-- src  
   `-- main  
     |-- java  
     |  `-- org  
     |    `-- fazlan  
     |      `-- jquery  
     |        `-- app  
     |          |-- domain  
     |          |  `-- Weather.java  
     |          `-- service  
     |            `-- WeatherService.java  
     |-- resources  
     `-- webapp  
       |-- img  
       |  `-- ajax-loader.gif  
       |-- index.jsp  
       |-- jquery.js  
       |-- jsp  
       |  |-- add_weather_ajaxprocessor.jsp  
       |  `-- list_weather_ajaxprocessor.jsp  
       `-- WEB-INF  
         `-- web.xml  

Step 1: Creating a the Web Project.

 mvn archetype:generate -DgroupId=org.fazlan -DartifactId=org.fazlan.spring.mvc -Dversion=1.0.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false  

Step 2: Updating the Maven Dependencies (pom.xml)

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
   <modelVersion>4.0.0</modelVersion>  
   <groupId>org.fazlan</groupId>  
   <artifactId>org.fazlan.jquery.app</artifactId>  
   <packaging>war</packaging>  
   <version>1.0.0-SNAPSHOT</version>  
   <name>org.fazlan.jquery.app Maven Webapp</name>  
   <url>http://maven.apache.org</url>  
   <dependencies>  
     <dependency>  
       <groupId>junit</groupId>  
       <artifactId>junit</artifactId>  
       <version>3.8.1</version>  
       <scope>test</scope>  
     </dependency>  
   </dependencies>  
   <build>  
     <finalName>jquery.app</finalName>  
     <plugins>  
       <plugin>  
         <groupId>org.mortbay.jetty</groupId>  
         <artifactId>maven-jetty-plugin</artifactId>  
         <version>6.1.10</version>  
       </plugin>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-compiler-plugin</artifactId>  
         <version>2.4</version>  
         <configuration>  
           <source>1.6</source>  
           <target>1.6</target>  
         </configuration>  
       </plugin>  
     </plugins>  
   </build>  
 </project>  

Step 3: Defining the Java Backend Logic

Weather.java
 package org.fazlan.jquery.app.domain;  
 public class Weather {  
   private String code;  
   private String city;  
   private String description;  
   private int temperature;  
   private int humidity;  
   public Weather(String code, String city, String description, int temperature, int humidity) {  
     this.code = code;  
     this.city = city;  
     this.description = description;  
     this.temperature = temperature;  
     this.humidity = humidity;  
   }  
   public String getCode() {  
     return code;  
   }  
   public String getCity() {  
     return city;  
   }  
   public String getDescription() {  
     return description;  
   }  
   public int getTemperature() {  
     return temperature;  
   }  
   public int getHumidity() {  
     return humidity;  
   }  
   @Override  
   public String toString() {  
     return "Weather{" +  
         "code='" + code + '\'' +  
         ", city='" + city + '\'' +  
         ", description='" + description + '\'' +  
         ", temperature=" + temperature +  
         ", humidity=" + humidity +  
         '}';  
   }  
 }  

WeatherService.java
 package org.fazlan.jquery.app.service;  
 import org.fazlan.jquery.app.domain.Weather;  
 import java.util.HashMap;  
 import java.util.Map;  
 public class WeatherService {  
   private static final Map<String, Weather> weather_map = new HashMap<String, Weather>();  
   static {  
     weather_map.put("SYD", new Weather("SYD", "Sydney", "Sunny", 22, 50));  
     weather_map.put("MEL", new Weather("MEL", "Melbourne", "Cloudy", 14, 45));  
     weather_map.put("QLD", new Weather("QLD", "Queensland", "Hot and Humid", 26, 65));  
     weather_map.put("PER", new Weather("PER", "Perth", "Sunny", 28, 55));  
     weather_map.put("ADL", new Weather("ADL", "Adelaide", "Mild", 18, 45));  
     weather_map.put("DWN", new Weather("DWN", "Darwin", "Sunny", 24, 45));  
     weather_map.put("TAS", new Weather("TAS", "Tasmania", "Cold", 12, 35));  
   }  
   public Weather get(String code) {  
     return weather_map.get(code);  
   }  
   public void add(Weather weather) {  
     weather_map.put(weather.getCode(), weather);  
   }  
 }  

Step 4: Defining the JSPs for Processing Requests
These JSP pages will act as Controllers, and invoke the backend business logic classes to process the requests.

list_weather_ajaxprocessor.jsp - This handles the requests for retrieving information related to the selected city from the dropdown.

 <%@ page import="org.fazlan.jquery.app.service.WeatherService" %>  
 <%@ page import="org.fazlan.jquery.app.domain.Weather" %>  
 <%!  
   // create an instance of the service  
   WeatherService weatherService = new WeatherService();  
   Weather weatherResult = null;  
 %>  
 <%  
   // get the selected city code from the request  
   String cityCode = request.getParameter("cityCode");  
   System.out.println("City Code: " + cityCode);  
   if (cityCode != null && !"".equals(cityCode)) {  
     // get the corresponding weather details for the requested citycode  
     weatherResult = weatherService.get(cityCode);  
     // delay to show the progress image in the UI using Ajax/jQuery  
     try {  
       Thread.sleep(2000);  
     } catch (Exception e) {  
     }  
   } else {  
     return;  
   }  
 %>  
 <!-- put the result into a HTML table and return that-->  
 <table width="500px">  
   <tr>  
     <td width="40%"><b>City</b></td>  
     <td style="color: blue;"><%= weatherResult.getCity() %>  
     </td>  
   </tr>  
   <tr>  
     <td width="40%"><b>Description</b></td>  
     <td style="color: blue;"><%= weatherResult.getDescription() %>  
     </td>  
   </tr>  
   <tr>  
     <td width="40%"><b>Temperature</b></td>  
     <td style="color: blue;"><%= weatherResult.getTemperature() %>  
     </td>  
   </tr>  
   <tr>  
     <td width="40%"><b>Humidity</b></td>  
     <td style="color: blue;"><%= weatherResult.getHumidity()%>  
     </td>  
   </tr>  
 </table>  

add_weather_ajaxprocessor.jsp - This handles the requests for submitting information related to the new city.
 <%@ page import="org.fazlan.jquery.app.service.WeatherService" %>  
 <%@ page import="org.fazlan.jquery.app.domain.Weather" %>  
 <%!  
   WeatherService weatherService = new WeatherService();  
 %>  
 <%  
   // get the form parameters  
   String code = request.getParameter("code");  
   String city = request.getParameter("city");  
   String description = request.getParameter("description");  
   int temperature = Integer.parseInt(request.getParameter("temperature"));  
   int humidity = Integer.parseInt(request.getParameter("humidity"));  
   // create a new Weather object and populate with the form values  
   Weather weather = new Weather(code, city, description, temperature, humidity);  
   // delay to show the progress image in the UI using Ajax/jQuery  
   try {  
     Thread.sleep(2000);  
   } catch (Exception e) {  
   }  
   // add the new Weather information  
   weatherService.add(weather);  
   // return the new city code to be added to the dropdown list  
   out.println("<option value=" + weather.getCode() + "> " + weather.getCity() + "</option>");  
 %>  

Step 5: Defining the Actual JSP View
Index.jsp
 <html>  
 <head>  
   <script type="text/javascript" src="jquery.js"></script>  
   <script type="text/javascript">  
     // jQuery document ready  
     $(function() {  
       /* jQuery event handling for city dropdown list */  
       $('#citySelect').change(function() {  
         $('#newEntryDiv').hide();  
         var cityCd = $(this).val();  
         $('#loadImg').show();  
         $.get(  
           'jsp/list_weather_ajaxprocessor.jsp',  
           {  
             cityCode: cityCd  
           },  
           function(data) {  
              $('#loadImg').hide();  
              $('#contentDiv').html(data);  
           });  
       });  
       /* jQuery event handling for adding a new city entry */  
       $('#addbtn').click(function() {  
         $('#newEntryDiv').show();  
         $('#contentDiv').html('');  
       });  
       /* jQuery event handling for submitting the new entry */  
       $('#newEntryForm').submit(function() {  
         $('#saveImg').show();  
         $.post(  
           'jsp/add_weather_ajaxprocessor.jsp',  
           $('#newEntryForm').serialize(),  
           function(data) {  
              $('#saveImg').hide();  
              $('#citySelect').append(data);  
              $('#newEntryDiv').hide();  
           });  
           clearForm($(this));  
         /*DO NOT REFRESH page after submit*/  
         return false;  
       });  
     });  
     /** function to clear the form */  
     function clearForm(form) {  
       $(":input", form).each(function() {  
         var type = this.type;  
         var tag = this.tagName.toLowerCase();  
         if (type == 'text') {  
           this.value = "";  
         }  
       });  
     }  
   </script>  
 </head>  
 <body>  
 <h1>Weather in Australia and Around the Globe</h1>  
 <div id="formDiv" style="border: 1px solid blue">  
   <table>  
     <tr valign="middle">  
       <td><b>Select City</b></td>  
       <td>  
         <form>  
           <select name="citySelect" id="citySelect">  
             <option value="">--- Select ---</option>  
             <option value="ADL">Adelaide</option>  
             <option value="DWN">Darwin</option>  
             <option value="MEL">Melbourne</option>  
             <option value="PER">Perth</option>  
             <option value="QLD">Queensland</option>  
             <option value="SYD">Sydney</option>  
             <option value="TAS">Tasmania</option>  
           </select>  
         </form>  
       </td>  
       <td><img src="img/ajax-loader.gif" style="display:none;" id="loadImg"/></td>  
     </tr>  
     <tr>  
       <td colspan="3">  
         <button id="addbtn" type="submit">Add New</button>  
       </td>  
     </tr>  
   </table>  
 </div>  
 <br>  
 <div id="newEntryDiv" style="display: none; border: 1px solid blue">  
   <form id="newEntryForm">  
     <table width="500 px">  
       <tr>  
         <td width="40%"><b>Code</b></td>  
         <td><input type="text" name="code"></td>  
       </tr>  
       <tr>  
         <td width="40%"><b>City</b></td>  
         <td><input type="text" name="city"></td>  
       </tr>  
       <tr>  
         <td width="40%"><b>Description</b></td>  
         <td><input type="text" name="description"></td>  
       </tr>  
       <tr>  
         <td width="40%"><b>Temperature</b></td>  
         <td><input type="text" name="temperature"></td>  
       </tr>  
       <tr>  
         <td width="40%"><b>Humidity</b></td>  
         <td><input type="text" name="humidity"></td>  
       </tr>  
       <tr>  
         <td><input type="submit"></td>  
         <td><img src="img/ajax-loader.gif" style="display:none;" id="saveImg"/></td>  
       </tr>  
     </table>  
   </form>  
 </div>  
 <div id="contentDiv" style="border: 1px solid blue">Weather information will appear here.</div>  
 </body>  
 </html>  


Step 6: Building and Deploying the Application

$ mvn clean install
$ mvn jetty:run

mvn:jetty:run - would run the web app on the jetty server.

Now, you can access the application with the following URL.
http://localhost:8080/org.fazlan.jquery.app/

Summary:
This article looked at how jQuery can be used to easily manipulate Javascript and simplify the usage of Ajax API.

The sample code can be found here.

No comments:

Post a Comment