Responding to Ajax Calls Using Servlets

By Rob Gravelle


Nothing says dynamic like Ajax calls. While server-side languages like .NET and PHP can generate context-sensitive content to a certain degree, once the page has been loaded into the browser, Ajax allows us to refresh specific elements of the document without reloading the entire page. Having a server component in place to handle the Ajax requests provides the additional flexibility of further processing power, database access, speed, and all the other benefits of full-fledged programming languages. In the Calling Servlets Using Ajax article, we learned how easy it is to bind an Ajax call to a Java Servlet to a button. In today's follow-up, we'll be writing the Java code, modifying the web.xml, and trying out our new Web app.

Generating a Servlet Class in Eclipse

This tutorial builds on the DynamicHTML5WebProject project that we created in the Create Dynamic HTML5 Web Content using Eclipse Juno article, so if you haven't done so already, follow the steps in that article to get the project up and running in Eclipse.

Create a Java Package

A servlet is really nothing more than a Java class that extends HttpServlet. Therefore, it would reside in a source folder under "Java Resources" in the Project Explorer. It's called "src" by default. We'll create a package for our servlet class because it is not recommended to put classes in the default package.

  1. Locate and right-click on the Java Resources/src folder in the Project Explorer.
  2. Select New > Package from the popup menu.
  3. On the New Java Package dialog, name the package "com.robgravelle.dynamichtml5webproject.servlet" and click Finish to create it. (Feel free to substitute your own domain name for the "robgravelle" part.)

Import the servlet-api.jar File

Eclipse needs to know about Servlet classes so that it can work with them in development mode. To do that:

  1. Right-click on the Project in Project Explorer and select Properties from the popup menu (it's the last item in the list).
  2. On the Properties for DynamicHTML5WebProject dialog, select the Java Build Path item from the left hand tree.
  3. Click on the Libraries tab.
  4. Click the Add External Jars… button and browse to the lib folder under your Jetty server installation. Mine is called "jetty-distribution-9.0.3.v20130506".
  5. Select the servlet-api-3.0.jar file and click the Open button to choose it. It should now appear in the Libraries list.
  6. Click OK to close the Properties for DynamicHTML5WebProject dialog.

Code the Java Servlet.

  1. Right-click on the new package in Project Explorer and select New > Class to create the servlet.
  2. On the New Java Class dialog, notice that creating the class in this way automatically populated the Package textbox.
  3. Give the class a name of "DynamicHTML5WebProjectServlet".
  4. Click the Browse… button beside the Superclass textbox to select the parent class.
  5. On the Superclass Selection dialog, type "httpservlet" in the "Choose a type" textbox to bring up "HttpServlet - javax.servlet.http" in the "Matching Items" list.
  6. Select it and click OK to close the dialog. The javax.servlet.http.HttpServlet class will now appear in the Superclass textbox.
  7. Click Finish to create the class and open it in the editor:
package com.robgravelle.dynamichtml5webproject.servlet;

import javax.servlet.http.HttpServlet;

public class DynamicHTML5WebProjectServlet extends HttpServlet {


Add a Default Serial ID

A warning will appear stating that "The serializable class DynamicHTML5WebProjectServlet does not declare a static final serialVersionUID field of type long". To fix it click on the light bulb in the margin and select "Add default serial version ID" from the popup menu. That will add the following constant to the class:

private static final long serialVersionUID = 1L;

Override the doGet() HttpServlet Method

Right-click anywhere in the editor and select Source > Override/Implement methods from the popup list.

On the Override/Implement Methods dialog, check the box beside the doGet() method and click OK to create the method stub:

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);

Replace the TODO comment and the call to super.doGet(req, resp) with the following code:

String name = req.getParameter("user");
if ("".equals(name)) { name = "there"; }

resp.getWriter().write("Hello " + name + "!");

In the above code:

  • A variable is declared and instantiated from the "user" input parameter that was sent from the Web form.
  • In the event that Submit button is clicked without a name provided, the name is set to a default value of "there".
  • The response content type is set to "text/plain".
  • The response character encoding is set to "UTF-8".
  • The greeting is sent back to the browser using the response writer's write() method.

Modify the web.xml file

The web.xml file contains configuration and deployment information for the web components of a web application. Locate it under WebContent/WEB-INF and open it in the editor. It will likely contain a list of default files:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" 
            id="WebApp_ID" version="2.5">

Every servlet requires mapping information. The following deployment descriptor defines an instance of the DynamicHTML5WebProjectServlet servlet and maps it to /DynamicHTML5WebProjectServlet/*. That pattern will cause the container to forward all requests that begin with /DynamicHTML5WebProjectServlet/ to our servlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" 
            id="WebApp_ID" version="2.5">
  <display-name>Dynamic HTML5 WebProject</display-name>

Starting Up the Server

I really like the run-jetty-run plugin because it makes launching the app a breeze. No more configuring the server and installing the project jars. All that's required is to select the DynamicHTML5WebProject project in Project Explore and choose Run > Run As > Run Jetty from the main menu:

Something like the following should appear in the console:

Running Jetty 6.1.26
2013-08-07 10:39:00.149:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
ParentLoaderPriority enabled
Context path:/DynamicHTML5WebProject
ProjectClassLoader: entry=C:\articles\HTMLGoodies\Eclipse\Web Apps\DynamicHTML5WebProject\build\classes
ProjectClassLoader: entry=C:\articles\HTMLGoodies\Eclipse\Web Apps\jetty-distribution-9.0.3.v20130506\lib\servlet-api-3.0.jar
ProjectClassLoader: entry=C:\articles\HTMLGoodies\Eclipse\Web Apps\DynamicHTML5WebProject\WebContent\WEB-INF\lib\standard.jar
ProjectClassLoader: entry=C:\articles\HTMLGoodies\Eclipse\Web Apps\DynamicHTML5WebProject\WebContent\WEB-INF\lib\jstl.jar
init scanning folders…
add to scan list:C:\articles\HTMLGoodies\Eclipse\Web Apps\DynamicHTML5WebProject\build\classes
add to scan list:C:\DynamicHTML5WebProject\WebContent\WEB-INF\web.xml
Starting scanner at interval of 5 seconds.
2013-08-07 10:39:00.259:INFO::jetty-6.1.26
2013-08-07 10:39:00.809:INFO::Started SelectChannelConnector@

Viewing the Page

To view your page in the browser:

  1. Choose which browser you want to use via the Window & Web Browser menu items.
  2. Click the Open Web Browser button on the main toolbar (It has the Earth icon).
  3. Type "http://localhost:8080/DynamicHTML5WebProject/" in the browser's Address box, where 8080 is the port that the server is listening on, as per the last line of server output above.

If all is well, something very much like this should come up (except with the actual date and time):


It is now: Wed, 2013-08-07 1:22:27 PM

Enter your name in the textbox and click on Submit to see the "Hello <yourname>!" greeting.

As basic as this application is, I think that you'll agree that there is the capability for great things using the combination of client and server-side technologies. This type of architecture lends itself extremely well to tasks such as searches, periodic content refreshes (think weather and stock quotes), and chatting apps.

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

Rob Gravelle resides in Ottawa, Canada, and is the founder of Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob 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 former 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 $1.95 per month, 2 LifeTime Free Domains, and 6 Months Free!

Make a Comment

Loading Comments...

  • 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