jQuery UI Dialog obtain content from Java Servlet AJAX request

jQuery dialog is basically a floating window with a title bar and a content area. It can be moved , resized and closed with the 'x' icon by default. In this example we create the dialog on the fly and dynamically populate the content from an AJAX request to a Java Servlet as well as set the title heading relevant to the content. We have discussed two different approaches here, either get the content after the user clicks on a given link or already load the dialog contents for the relevant links when page is loading. Depending on your business requirement you can choose to implement either scenario.


jQuery dynamic UI Dialog using AJAX request
jQuery dynamic UI Dialog box content

Java Object Source

package com.as400samplecode.util;

public class Country {
 
 String code = null;
 String name = null;
 String continent = null;
 String region = null;
 Double lifeExpectancy = null;
 Double gnp = null;
 
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getContinent() {
  return continent;
 }
 public void setContinent(String continent) {
  this.continent = continent;
 }
 public String getRegion() {
  return region;
 }
 public void setRegion(String region) {
  this.region = region;
 }
 public Double getLifeExpectancy() {
  return lifeExpectancy;
 }
 public void setLifeExpectancy(Double lifeExpectancy) {
  this.lifeExpectancy = lifeExpectancy;
 }
 public Double getGnp() {
  return gnp;
 }
 public void setGnp(Double gnp) {
  this.gnp = gnp;
 }

 
} 

Java Servlet for our AJAX request

package com.as400samplecode;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.as400samplecode.util.Country;

public class GetCountryDetail extends HttpServlet {

 private static final long serialVersionUID = 1L;

 public GetCountryDetail() {
  super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request,response);
 }

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

  String countryCode = request.getParameter("countryCode");
  
  PrintWriter out = response.getWriter();
  response.setContentType("text/html");
  response.setHeader("Cache-control", "no-cache, no-store");
  response.setHeader("Pragma", "no-cache");
  response.setHeader("Expires", "-1");

  StringBuffer sb = new StringBuffer();
  Country country = getDetailInfo(countryCode);
  
  sb.append("<table>");
  sb.append(addContent("Code: ", country.getCode()));
  sb.append(addContent("Continent: ", country.getContinent()));
  sb.append(addContent("Region: ", country.getRegion()));
  sb.append(addContent("GNP: ", String.valueOf(country.getGnp())));
  sb.append(addContent("Life Expectancy: ", String.valueOf(country.getLifeExpectancy())));
  sb.append("</table>");
  
  out.println(sb.toString());
  out.close();

 }
 
 private String addContent(String label, String value){
  
  return "<tr>" +
    "<td>" + label + "</td>" +
    "<td>" + value + "</td>" +
    "</tr>";
  
 }

 //Get Country Information
 private Country getDetailInfo(String countryCode) {

  Country country = new Country();
  Connection conn = null;             
  PreparedStatement stmt = null;      
  String sql = null;

  try {       
   Context ctx = (Context) new InitialContext().lookup("java:comp/env");
   conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection(); 

   sql = "Select * from country where code = ?"; 
   stmt = conn.prepareStatement(sql);
   stmt.setString(1, countryCode.trim());
   ResultSet rs = stmt.executeQuery();  

   while(rs.next()){ 
    country.setCode(rs.getString("code").trim());
    country.setName(rs.getString("name").trim());
    country.setContinent(rs.getString("continent").trim());
    country.setRegion(rs.getString("region").trim());
    country.setLifeExpectancy(rs.getString("lifeExpectancy") == null ? new Double(0) : Double.parseDouble(rs.getString("lifeExpectancy").trim()));
    country.setGnp(rs.getString("gnp") == null ? new Double(0)  : Double.parseDouble(rs.getString("gnp").trim()));
   }                                                                          

   rs.close();                                                                
   stmt.close();                                                              
   stmt = null;                                                               


   conn.close();                                                              
   conn = null;                                                    

  }                                                                
  catch(Exception e){
   e.printStackTrace();
  }                       

  finally {                                                        
   
   if (stmt != null) {                                             
    try {                                                          
     stmt.close();                                                 
    } catch (SQLException sqlex) {                                 
     // ignore -- as we can't do anything about it here            
    }                                                              

    stmt = null;                                             
   }                                                         

   if (conn != null) {                                       
    try {                                                    
     conn.close();                                           
    } catch (SQLException sqlex) {                           
     // ignore -- as we can't do anything about it here      
    }                                                        

    conn = null;                                             
   }                                                         
  }               

  return country;

 } 

}

jQuery Source for dialog UI

<%@ 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">
<meta name="robots" content="noindex,nofollow" />
<title>Display dialog box after loading content using AJAX</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />
<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {

 //get the content after user clicks
 $('.myList li > a').click(function(event){

  var el = $(this);
  var divTag = $("<div></div>");
  var myTitle = $(this).attr('title');   
  $.ajax({
      url: '../GetCountryDetail?countryCode=' + $(this).attr('href'),
      success: function(data) {
        divTag.html(data)
         .dialog({
          modal: true,
          title: myTitle,
          show: "blind",
          hide: "explode",
          position: { 
          my: 'top',
          at: 'bottom',
          of: el
             }

         })
         .dialog('open');
      }
  });
  return false; 
 
 });
 
 //get the content when the page loads
 $('button').each(function() {
  
  var divTag = $("<div></div>");
  var myTitle = $(this).attr('title'); 
  divTag.load('../GetCountryDetail?countryCode=' + $(this).attr('value'))
       .dialog({
        modal: true,
        autoOpen: false,
        title: myTitle,
        show: "blind",
            hide: "explode"
       });
 
  $(this).click(function() {
   divTag.dialog('open');
   return false;
  });
  
 });
 
});
</script>
</head>
<body>
 <div id="allContent">
  <div id="myContent">
   <fieldset>
    <legend><b>&nbsp;&nbsp;&nbsp;jQuery UI Dialog demo using AJAX&nbsp;&nbsp;&nbsp;</b></legend>
     <p>
      <b>List of some countries ...</b>
     </p>
     <ul class="myList">
      <li>
       <a href="FRA" title="France">France</a>
      </li>
      <li>
       <a href="DEU" title="Germany">Germany</a>
      </li> 
      <li>
       <a href="CAN" title="Canada">Canada</a>
      </li>
     </ul>
     <p>
      <b>List of some countries in buttons...</b>
     </p>
     <button value="USA" title="United States">United States</button> 
     <button value="BRA" title="Brazil">Brazil</button>
     <button value="CHN" title="China">China</button>
   </fieldset>
  </div>
 </div>

 <div></div>
</body>
</html>

References


2 comments :