Developing Web Application with JQuery and Java Servlet

It’s been a while since I touched Web application development in 2009. Before the VMworld 2009, I created a simple Web Application for the keynote that collected the names and email for a raffle to go back stage with the famous foreigner. That Web application was so simple that it’s built using Java Servlet with a static home page. It’s hosted with Terremark (part of Verizon now) Enterprise cloud.

During the Christmas time, things slowed down and I had time to learn something new. I picked JQuery this time, not only for my own technical curiosity but also because it’s been used in one of our projects at work. Learning something related to project always helps – there are plenty of chances to practice it afterwards which is key to retain the newly learned skills.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

While learning the JQuery, I started with a very simple JQuery page, the Hello World kind. Here is one simple sample I modified from the JQuery tutorial. Instead of registering click event on the link, I changed it to mousemove event.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
 <head>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
 <script type="text/javascript">
	$(document).ready(function() {
		$("a").mousemove(function() {
		   alert("Hello World!");
		});
	});
 
 </script>
 </head>
 <body>
	<a href="">Link</a>
 </body>
 </html>

As you can see, the “Hello World” works fine but it doesn’t really solve any problem. To make it useful, it got to connect to the backend Web server. I picked the Java Servlet as I am already familiar with it (it took me a little bit time to refresh myself to the 3.0 features like annotation).

To better learn it, I tried to write a simple Web application that shows stock prices with AJAX calls. As the key to learn the interaction of JQuery and Java Servlet, I didn’t include any code to connect to database. Rather, I just hardcoded a few stocks. I included the two files required for the simple project. I can run on any Java Servlet 3.0 compatible container like Tomcat 7.

Here are a few lessons learned from my playing with this simple application:

JavaScript Syntax

JavaScript is pretty hard to get right on syntax, especially the closing brackets for blocks (}) and functions ()). Coming from Java background, I expect it’s checked for you by the IDE. There may be some plugins to IDEs like Eclipse helping on that. I used Eclipse WTP with no such luck. The worst case is that when the syntax is wrong, the JavaScript just fails silently. I later on used IE debugger (just press F12 to bring it up) and that helped.

Without typing support, it’s critical to format the JQuery code in a nice way with right level of indentation. I found myself missing or having extra closing marks frequently. It can be even more frequently when you copy/paste code from one file to another. It always helps to format the JQuery code to catch errors before running it.

AJAX Caching

AJAX call won’t call every time as you expect because of caching. By default, the cache is on. It puzzled me why it only worked the first time and then I no longer got request on the servlet side. After playing around including shutting down tomcat and even IDE and searching the API docs, I realized that I have to turn off the cache so that my call is issued every time as I expected.

JSON Parsing

The JSON call fails silently if it cannot parse the response. I initially used getJSON() method and couldn’t figure out why my function is called. It turned out that the JSON response has to be in right format ( check here for official samples ) or it won’t be called. For example, I misused the single quotation mark for double quotation mark in the JSON response in my servlet. I had no clue on what happened.

After searching StackOverflow, I switched to the .ajax call, which offers more hooks on error and completion so that I can catch parsing errors. I don’t think you will likely get JSON format issue because you will most likely use JSON library to serialize the JSON object in real projects. But the point here is that you can use the lower level .ajax call for more insights while debugging. Notice the difference of success and complete events: the success, as its name suggests, is triggered only if the HTTP return 200 OK; while the complete no matter what. The complete function gets called after success as pointed out in this link.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!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>Java and JQuery with JSON - doublecloud.org</title>
    <script type="text/javascript" src="javascript/jquery/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(document).ready(function()
      {
        $("#getStockPrice").click(function()
        {
          $stock = $("#stock").val();
          $.ajax({
            url: 'StockServlet',
            dataType: 'json',
            data: {stock: $stock},
            type: 'get',
            cache: false,
            success: function(response)
            {
              var infoHTML = '';
              $.each(response, function(stock, stockInfo)
              {
                infoHTML += '<p>Symbol: ' + stock + "   Company: " + stockInfo.name + '   Price: ' + stockInfo.price + '</p>';
              })
              $("#stockReport").html(infoHTML);
            },
            error: function(request, textStatus, errorThrown)
            {
              alert("error:" + textStatus);
            },
            complete: function(request, textStatus)
            {
              alert("complete" + request.responseText);
              alert("complete" + textStatus);
            }
          });
        });
      });
    </script>
  </head>
 
  <body>
    Enter Stock Symbols:
    <input id="stock" name="stock" size="40" type="text" />
    <input id="getStockPrice" name="getStockPrice" type="button" value="Get Stock Price" />
    <div id="stockReport" class="outputTextArea"></div>
  </body>
</html>

Java Servlet code: StockServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet(asyncSupported = false, name = "StockServlet", urlPatterns = {"/StockServlet"})
public class StockServlet extends HttpServlet 
{
  private static final long serialVersionUID = 1L;
 
  public StockServlet()
  {
    super();
  }
 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  {
    System.out.println("in StockServlet");
    String stocks = request.getParameter("stock");
    String report = getStocks(stocks);
    System.out.println(report);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write(report);
    out.flush();
    out.close();
  }
 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  {
  }
 
  private String getStocks(String stocks) 
  {
    String jsonStocks = "{ ";
 
    StringTokenizer st = new StringTokenizer(stocks, ",");
 
    while(st.hasMoreElements())
    {
      String stockSymbol = (String) st.nextElement();
      stockSymbol = stockSymbol.trim().toLowerCase();
 
      if("csco".equals(stockSymbol))
      {
        jsonStocks = jsonStocks + "\"csco\": {\"name\": \"Cisco Systems\", \"price\": \"$20\" },";
      }
      else if("vmw".equals(stockSymbol))
      {
        jsonStocks = jsonStocks + "\"vmw\": {\"name\": \"VMware\", \"price\": \"$90\" },";
      }
      else if("emc".equals(stockSymbol))
      {
        jsonStocks = jsonStocks + "\"emc\": {\"name\": \"EMC Corp.\", \"price\": \"$25\" },";
      }
      else
      {
        jsonStocks = jsonStocks + "\"" + stockSymbol + "\": {\"name\": \"Unknown\", \"price\": \"NA\" },";
      }
    }
 
    if(jsonStocks.charAt(jsonStocks.length()-1)==',')
    {
      jsonStocks = jsonStocks.substring(0, jsonStocks.length()-1);
    }
 
    return jsonStocks + "}";
  }
}
This entry was posted in Software Development and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

5 Comments

  1. Posted December 27, 2012 at 11:49 pm | Permalink

    Developing Web Application with JQuery and Java Servlet http://t.co/leizp57h via @sjin2008

  2. Posted December 28, 2012 at 12:49 am | Permalink

    Developing Web Application with JQuery and Java Servlet (DoubleCloud) http://t.co/rPOrMl4A

  3. Posted December 28, 2012 at 3:53 pm | Permalink

    Developing Web Application with JQuery and Java Servlet … http://t.co/3X9bTsjQ #web

  4. Posted February 24, 2016 at 7:57 am | Permalink

    nice post

  5. abhishek kumar
    Posted June 17, 2016 at 6:05 am | Permalink

    I don’t know

One Trackback

  • […] famous foreigner. That Web application was so simple that it’s built using Java Servlet with […]Developing Web Application with JQuery and Java Servlet originally appeared on DoubleCloud by Steve Jin, author of VMware VI and vSphere SDK (Prentice […]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.