Servlets and Java Server Pages


Based on chapter 16 in the book "Just Java 2" by Peter van der Linden

More information about Servlets is available at Sun's web site.

It is very useful to be able to provide web pages whose content will change dynamically according to the request by the user.
In the HTML protocols, there are two methods to capture information in a form from the user:
  1. get
  2. post
When one writes a web page that will capture information from a user, one specifies which method will be used.
The following example illustrates how to capture a word in a web page. The method used here is GET,
which is specified at the beginning of the form tag.
To actually capture the input from the user, two components are used here:
A text field and a button (submit) that will trigger the sending of the web page to the server.
The piece of SW in charge of handling this request is specified in the first tag of the form, in the field action.

<html>
<body>
<center>
        <h1>An English-Spanish Dictionary</h1>
</center>
<form action=/examples/servlet/DictServlet method=GET>
<h4>
        Enter the word in English:
</h4>
<input type=text name=word size=15>
<input type=submit value="Translate">
</form>
</body>
</html>

Servlets are another alternative to handle requests to handle GETs or POSTs.  Other alternatives include cgi-bin, ASP,  PHP, and pearl scripts.

Servlets are pieces of SW written in Java that will be invoked by the Web server.

Apache is an Open Source Web Server.
One of the subprojects of Apache is Jakarta, a web server written in Java. Jakarta can be configured to work in conjunction with another (faster) web server, but it can be installed as a standalone utility to experiment with servlets. Jakarta will enable other web servers to support servlets.

The documentation about servlets is available here.
There are servlets that are capable of serving requests for other kinds of services, not only http.
There is a class of servlets that specializes on providing http services called HttpServlet.

To write one's own servlet, one extends HttpServlet and overrides the appropriate methods.
There are three methods that can be overridden in a class derived from HttpServlet:
  1. init(): To initialize the servlet
  2. doGet(...): To handle gets 
  3. doPost(...): To handle posts
Both doGet and doPost will have two parameters:
The request has all the information provided by the web page that requested the service.
The response has all the fields and methods required to form an answer.

One uses the method getWriter() in the response parameter to obtain a writer that can be used to build the web page that will be sent as an answer to the request.

The following code illustrates these ideas:


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

public class DictServlet extends HttpServlet {
    // Instantiate an object of the class Dictionary
    MyDictionary dictionary = new MyDictionary();

    public void doGet(HttpServletRequest req,
                      HttpServletResponse resp)
        throws ServletException, IOException {
        String wordInEnglish;

        // Read the word from the form submitted by the browser
        wordInEnglish = req.getParameter("word");
        // Look up the word in the dictionary
        String result = dictionary.find(wordInEnglish);
        if (result == null)
            result = "Word not found";
        // Build the response
        resp.setContentType("text/html");

        PrintWriter out = resp.getWriter();

        out.println("<html> <body> <h1> Translation </h1> <p>");
        out.println("The translation for "+wordInEnglish+" is "+result);
        out.println("<hr> </body> </html>");

        out.close();
    }
}
/**
 * MyDictionary
 *
 * @author  Christian Trefftz
 * @version Fall 2002
 */
import java.io.*;
import java.util.HashMap;
public class MyDictionary
{
    HashMap map = new HashMap();
    public MyDictionary()
    {
        map.put("cat","gato");
        map.put("dog","perro");
    } // End Constructor

    public String find(String key)
    {
        return (String)map.get(key);
    }
}

To illustrate how this servlets work, we will use Jakarta on one of the EOS lab machines.
It has been installed in stand alone mode, it is not connected to Apache.
For this example, assume that we are working on the machine eos03.

To start Jakarta, we move into the subdirectory jakarta-tomcat-4.0/bin

Because we are in a Linux environment, we use the script:
 startup.sh

The web page described before, has been placed in the subdirectory
 jakarta-tomcat-4.0/webapps/examples/servlets

It is called mydictionary.html.

To find this web page, we type in a browser (after starting jakarta):
 http://eos03.csis.gvsu.edu:8080/examples/servlets/mydictionary.html

The servlet DictServlet was placed in the directory
 jakarta-tomcat-4.0/webapps/examples/WEB-INF/classes

The class MyDictionary was placed in the same directory.

Before, logging off from eos03, we should run, in the directory jakarta-tomcat-4.0/bin
 shutdown.sh

Other examples of Servlets are included with Jakarta and can be found at
 http://eos03.csis.gvsu.edu:8080/examples/servlets/

The examples show how to examine the headers and the parameters arriving in a page, how to use cookies and how to keep track of sessions.

Java Server Pages

More information about Java Server Pages can be found at Sun's site.

Java Server Pages allow HTML developers to include Java code directly in a page.

The code is then converted into an appropriate servlet and the output is included in the resulting web page that is displayed by the browser.

Special tags in the html documents identify what to do:
<%
Everything up to the closing tag %> is java code
<%=
Evaluates the Java expression that follows, converts it to a String and writes it to the HTML output
<%!
A java declaration. Available to all methods in the servlet
<%@
Can be followed by one of several different strings, such as method, import, extends. Useful for the generated Java
<jsp: useBean \>
Invokes a Java Bean

Several examples of  JSPs are included in Jakarta in the subdirectory:
jakarta-tomcat-4.0/webapps/examples/jsp/