Calling Servlets Using Ajax

By Rob Gravelle


Is Java Dead?

Some proponents of the up-and-coming Web developing community are of the opinion that Java, servlets, and JSPs are an ancient and thus obsolete technology, a dinosaur that is all but extinct. As the senior technical advisor for Java coding practices for Canada Border Services, I can vouch for the fact that Java and it's associated technologies are very much still at the forefront of Web development - particularly in the realm of large-scale Enterprise level applications, where security and accuracy are paramount. Users of Java tend to be large institutions like banks, aerospace, and government. Depending on the source, Java may rank anywhere in the top ten. For instance, one list on FreeRepublic.com puts it at the top for 2012. I would certainly rate it in the top five. To summarize, Java is sexy, and it will continue to be for a good while yet.

Updating the index.html File

Assuming that you've completed the the previous tutorial, you should have a Dynamic Web Project named "DynamicHTML5WebProject". Open it in Eclipse and bring up the index.html file using the JSP Editor.

Remove the <c:out> tag that prints "Hello World" because that's the message that we will be customizing.

Add a form to the document with an ID of "frmUser".

In the form, add add the following controls:

  • A label for "txtName".
  • An input of type text with an ID of "txtName".
  • An input of type button with an ID of "btnSubmit" and a value of "Submit".
  • An empty DIV with an ID of "welcometext". It will display the customized message.

Add a couple of breaks between the button and the welcometext DIV. Your document body should now look as follows:

        <p>It is now: <fmt:formatDate value="<%=new java.util.Date()%>" pattern="E, yyyy-MM-dd h:mm:ss a" /> </p>

        <form id="frmUser">
                <label for="txtName">Enter your Name:</label> 
                <input type="text" id="txtName" /> 
                <input type="button" id="btnSubmit" value="Submit" />
                <br />
                <br />
                <div id="welcometext"></div>

The JavaScript Code

So far, the submit button doesn't do anything because there is no code attached to it. On the client-side, we're going to write some jQuery-powered JavaScript to perform the Ajax call to a servlet. Why jQuery? Well, it just so happens that Eclipse supports auto-completion for jQuery, thanks to the jsdt-jquery plugin. My Add External JS Libraries to Eclipse JSDT-driven Projects article describes how to install the plugin and add the jQuery Object Model Library to your project, so I won't repeat everything here. Follow the directions and we'll see you back here when you're done.

We'll place all of the JavaScript code in it's own file so that the client-side behavior (.js) is separate from presentation (.jsp). Right-click on the DynamicHTML5WebProject\WebContent folder in the Project Explorer and select New > Other from the popup menu to open the "New" Wizard.

Type "JavaScript" in the Wizards filter box and select "JavaScript Source File" in the list.

Click the Next button.

Name the file the same as the project ("DynamicHTML5WebProject") and click Finish. Eclipse will append the .js extension automatically as well as open the file in the editor pane.

Begin by typing "$(document)." in the file and the auto-complete should kick in after the dot:

Select the ready() function. Inside the parentheses, add the following anonymous function, which includes the submit button handler that initiates the Ajax call:

$(document).ready(function() {               
    $('#btnSubmit').click(function(event) {  
        var username=$('#txtName').val();
        $.get('DynamicHTML5WebProjectServlet',{user:username},function(responseText) { 

Pretty neat eh?

The Servlet Code

Servlet classes are part of the javax.servlet package and are not a part of Java Standard Edition. Therefore, if you're not running Java Enterprise Edition (Java EE), you'll have to add the jar to the project. Jetty has them in the servlet-api-2.5-20081211.jar. You may have to perform a search on your workstation to find it. Mine was located in the "<eclipse root>\configuration\org.eclipse.osgi\bundles\806\1\.cp\lib" folder.

To add the servlet classes to the project:

  1. Right click on the project in Project Explorer and select Properties from the popup menu (it's at the bottom).
  2. On the "Properties for DynamicHTML5WebProject" dialog, click on Java Build Path in the left-hand tree.
  3. Click the Libraries tab.
  4. Click the "Add External Jars" button, browse to your servlet jar file, select it and click Open to choose it and close the Browse dialog.
  5. Back on the "Properties for DynamicHTML5WebProject" dialog, you should now see the jar in the libraries list. Click the OK button to close the dialog.


That takes care of the client-side code. In the next instalment, we'll be writing the Java code, modifying the web.xml, and trying out our new Web app.

If you enjoyed this article, please contribute to Rob's rock star aspirations by purchasing one of Rob's cover or original songs from iTunes.com for only 0.99 cents each.

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleWebDesign.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. EmailRob to receive a free estimate on your software project.

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92).

Rob uses and recommends MochaHost, which provides Web Hosting at $3.10 per month, 2 LifeTime Free Domains, and 6 Months Free!

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date