Previous
Index

Next

7.2) What makes servlets work?

What is a Servlet?

A servlet is a Java program that runs on an internet server. The document that sets the specification for how to write a servlet is called the Servlet Specification and can be found at

http://www.jcp.org/aboutJava/communityprocess/final/jsr154/

The servlet specification is more readable than many specification documents but is still not a “laugh a minute read”.

Unlike JavaScript which is code that executes within the browser on your local machine a Servlet is entirely independent of the client computer (the one you sit at when accessing a web site). Thus from the perspective of your web browser it is just seeing HTML pages and it has no knowledge of the fact that it is the Java program that is generating those pages. A servlet is a Java program written explicitly to respond to web requests, typically an end user clicking on something on a web browser. In some ways servlets are similar to older technologies such as Perl/CGI because they execute on the server, but in others they are very different because servlets are very tightly integrated into the servlet container (the program such as Tomcat they execute within).

One of the other important features of Servlets is that they are multi-threaded. When a request comes into the web container, instead of starting an entire new process the container simply starts a new thread or it assigns a thread from its pool of exiting threads. Because threads are lightweight processes this means it requires fewer resources. It also means that you cannot make assumptions about thread safety, but for most purposes, and certainly for the purposes of this version of the exam, you don't need to worry about that.

To illustrate a simple servlet the following code will output the traditional

“Hello World” message.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloGet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* The heart of the servlet */
        PrintWriter pw = response.getWriter();
        pw.println("<html>");
        pw.println("<h1> Hello World </h1>");
        pw.println("</html>");
    }
}

Don't try to create and compile that code, because some more “magic” needs to be done to make it actually work. Just read it to get an idea of what packages you need to import, the name of the service method the details of the objects that are passed to the service method.

The part that really makes the servlet work is contained within the doGet method. This is effectively called not by the client request but by the Container (Tomcat in this case) in response to a request from a web browser. The link between the Servlet and the request from the web browser is the instances of HttpServletRequest and HttpServletResponse that are passed in as parameters to the doGet method. As you might guess these contain all the information associated with the HTTP request and response that are in the request sent from the web browser (e.g. Firefox or Internet Explorer).

The key to the action is the instance of PrintWriter obtained by the instance of HttpServletResponse passed by the service method. Note how the a servlet knows very little about the idea of HTML and simply treats it as text to be sent to an output stream. If this seems unusually crude or if you are used to systems such as ASP/PHP,don't worry, when we come to JSP later on you will see how you can embed logic within standard HTML where that is appropriate. To understand how servlets work you need to know a little about the HTTP GET and POST methods and the matching servlet methods.

HTTP GET and the doGet method

Just about every servlet you write will override at least either doGet or doPost or possibly both. The HTTP GET method is one of the most commonly used HTTP methods. It is called whenever the user of a web browser clicks on a hyper-link or types in a URL into the address bar. A get request may also include additional parameters such as

http://www.mysite.com/login.htm?username=someone&type=student

Note how the first parameter is indicated by a question mark and the second is indicated by the ampersand marker. One of the benefits of the get method is that it can be saved as a short cut (bookmark). When a web browser sends an HTTP GET method a servlet that processes it will direct processing to the doGet method of the servlet.

HTTP POST and the doPost method

The HTTP POST method is usually configured to be the method triggered when a user clicks on a control within a form. I say “is usually configured” because the default method of a form is actually a GET call but this is very rarely what is wanted. The benefit of the HTTP POST method is that it sends any parameters within the body of the method rather than in the URL bar. This makes the parameters less obvious and allows more parameters to be transmitted in some browsers. When a servlet receives a request that contains an HTTP POST method it is redirected to the doPost method of the servlet. If the servlet has no implementation of the doPost (or doGet) method the call will be redirected to the implementation in the parent HtttpServlet class which is a “do nothing” version.

WEB-INF and WEB.XML

Every complete web application (i.e. one that includes servlets as well as JSP files) must include WEB-INF directory. This directory must exist off the root and files within it are not directly visible from a web browser. Thus if you have an html file within that directory you cannot request it with a url like

http://www.mydomain.com/WEB-INF/index.htm

Servlets are stored under the WEB-INF directory and it is good practice to put them in proper package structure. Thus for my sample code associated with my www.examulator.com web site I create a directory structure as

\mywebapp\WEB-INF\com.examulator\myservlet.class

To make life easier I recommend you use NetBeans to create your servlet and the package structure.

I said earlier that more “magic” would be required to actually make that servlet work. The magic is mainly a case of adding entries to a file called WEB.XML which is also known as the deployment descriptor. When you create a web application with NetBeans it automatically creates a WEB-INF and deployment descriptor file (WEB.XML).

The deployment descriptor must contain two entries to make a servlet executable from a web browser. If you use a tool like NetBeans to create a servlet it will make the entries in WEB.XML that will make it executable. However it is important to understand what the entries mean in case things get broken or you need to modify an existing configuration. NetBeans provides a GUI editor for the desployment descriptor (WEB.XML), which is very useful for ensuring the structure is correct. However to understand what is actually happening I recommend you click on the XML tag so you can see the actual tags that are being manipulated.

Every servlet must have a servlet entry and servlet-name and servlet-class entries. Here is an example of a complete servlet tag.

<servlet>
  <servlet-name>HelloGet</servlet-name>
  <servlet-class>com.examulator.HelloGet</servlet-class>
</servlet>

The servlet tag sets up a link between the fully qualified class name and a short name that is used elsewhere in the deployment descriptor when referring to the servlet.

The minimal other requirement is a servlet mapping to the url where it will be accessed.

 <servlet-mapping>
        <servlet-name>HelloGet</servlet-name>
        <url-pattern>/HelloGet</url-pattern>
    </servlet-mapping> 

This mapping matches the name HelloGet with the url /HelloGet.

Thus the following will set up the HelloGet servlet to be accessed from a browser as

http://localhost:8084/WebApplicationName/HelloGet

To break down this URL into its parts the http:// says this request is using the HTTP protocol, the same as for just about every web page. The word localhost is reserved to indicate that the browser is accessing a server running on the local machine (the same as the browser). The 8084 part indicates that the service that is being accessed on the Tomcat server runs on port 8084. Normally a web browser accesses web pages via port 80. Because port 80 is the default it is not normally shown in the URL bar. You can check out that port 80 is the default by putting it into any standard URL. Thus the following

http://www.google.co.uk:80

Will access google without error.

The WebApplicationName just gives you a convenient virtual directory to contain the components of your application. Note how the name of the actual servlet has no extension i.e. it doesn't have .class at the end.

Create a web application in NetBeans

Once you have NetBeans running create a new project selecting the Web type of project. The first step of creating the web application asks a sequence of questions that c
an mostly be left to their defaults. However to keep things simple change the server from GlassFish to Apache Tomcat.

This will produce a directory structure to store the various components of a Web application. By default the creation of a web application creates a default JSP page called index.jsp which you can safely ignore for the moment.To create the directory structure/package click on the Source Packages node of the application and click the right mouse button.




You can create the directory structure in one statement, i.e. enter com.examulator and it will create the directories either

com\examulator

on a Microsoft platform

or

com/examulator

On a Unix style platform.

Once you have created the package you can use NetBeans to create a default Servlet that will execute without additional editing.

Dealing with parameters

As part of the HTTP protocol a URL can terminate with parameters to pass information to the requested page.

According to page 35 of the servlet specification

"Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request."

Thus for example if I put the following URL into my browser

http://maps.google.co.uk/maps?hl=en

Google knows to display the text on the page in the English language. If the en is change to fr the page will be displayed in French.

A servlet can retrieve parameters using the getParameter method of the HttpServletRequest interface. Because doGet and doPost take an instance of HttpServletRequest the method can be called directly within the body of doGet or doPost. The following code illustrates this.

package com.examulator;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class GetLang extends HttpServlet {
    protected void doGet(HttpServletRequest request, 		HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        String lang = request.getParameter("lang");
        pw.println("Language ="+lang);
    }
}

When this Servlet is run it will retrieve the value of the lang parameter passed to it. Thus if it is called with the URL as

http://localhost:8084/WebApplication1/GetLang?lang=en

The output in the browser will be

Language =en

Your first JSP

When you created your web application it created a default index.jsp page. This appears under the Web Pages node of the application. When NetBeans creates the default web application it actually creates a minimal simple JSP page by default which you can run in your browser just to see the whole compilation/execution cycle.

At its simplest a JSP is simply an HTML page with some tags that allow plain Java to be inserted. Thus the following would be a legitimate tag within a JSP page.

<%
System.out.println(“Hello world”);
%>

When the Web container processes a page with those tags, each time it gets to an opening <% it knows it is has to turn the ensuing statements into Java code in the servlet that is generated. Where Java is included within a JSP it is called a scriptlet.

You can run this page by clicking on the file, click the right mouse button and choose run. The following steps then happen

During the start up of the local version of Tomcat you will see the output of each step as the page gets ready to run the JSP.

You can see the servlet generated from the JSP page by clicking on the JSP file and selecting the view servlet option. You probably won't need to ever actually look at the generated servlet when programming but it is interesting to see how the system converts the JSP statements into servlet code. Note that you should never edit the generated servlet.

Getting Parameters into a JSP

A JSP can retrieve parameters in a similar way to a servlet. A JSP includes a number of “implicit objects”, i.e. objects that are provided without having to write any code. Two of these objects are request and response which map to the request and response parameters that are passed to the doGet and doPost methods of servlets. The following code will retrieve parameters passed to a JSP

		<%
        out.print("Language=" +request.getParameter("lang"));
%>

Other sources

API Docs for HttpServletRequest
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html

Deploying web applications to Tomcat by James Goodwill
http://www.onjava.com/pub/a/onjava/2001/04/19/tomcat.html?page=2

VisualBuilder tutorial on JSP
http://www.visualbuilder.com/jsp/tutorial/

http://www.examulator.com/fjt



Previous
Index

Next