Advanced Java Module 4
Advanced Java Module 4
Module 4
Introducing Servlets
Servlets are small programs that execute on the server side of a web connection.
4.1 Background
In order to understand the advantages of servlets, you must have a basic understanding of
how web browsers and servers cooperate to provide content to a user.
Consider a request for a static web page.
A user enters a Uniform Resource Locator (URL) into a browser. The browser
generates an HTTP request to the appropriate web server.
The web server maps this request to a specific file. That file is returned in an HTTP
response to the browser.
The HTTP header in the response indicates the type of the content.
The Multipurpose Internet Mail Extensions (MIME) are used for this purpose.
For example, ordinary ASCII text has a MIME type of text/plain. The Hypertext
Markup Language (HTML) source code of a web page has a MIME type of text/html.
It communicated with the web server via an interface known as the Common Gateway
Interface (CGI).
CGI allowed the separate process to read data from the HTTP request and write
data to the HTTP response. A variety of different languages were used to build CGI
programs. These included C, C++, and Perl.
However, CGI suffered serious performance problems.
It was expensive in terms of processor and memory resources to create a separate
process for each client request. It was also expensive to open and close database
connections for each client request.
In addition, the CGI programs were not platform-independent.
Therefore, other techniques were introduced.
Among these are servlets.
Servlets offer several advantages in comparison with CGI.
First, performance is significantly better. Servlets execute within the address space
of a web server. It is not necessary to create a separate process to handle each client
request.
Second, servlets are platform-independent because they are written in Java.
Third, it is possible to enforce a set of restrictions to protect the resources on a server
machine.
Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with other software via the sockets and RMI mechanisms that you have
seen already.
Third, the server invokes the init( ) method of the servlet. This method is invoked only
when the servlet is first loaded into memory. It is possible to pass initialization
parameters to the servlet so it may configure itself.
Fourth, the server invokes the service( ) method of the servlet.
This method is called to process the HTTP request.
You will see that it is possible for the servlet to read data that has been provided in the
HTTP request. It may also formulate an HTTP response for the client.
The servlet remains in the server’s address space and is available to process any other
HTTP requests received from clients.
The service( ) method is called for each HTTP request. Which this determination is
made are specific to each server.
The server calls the destroy( ) method to relinquish any resources such as file handles
that are allocated for the servlet.
Important data may be saved to a persistent store.
The memory allocated for the servlet and its objects can then be garbage collected.
IDEs such as NetBeans and Eclipse are very useful and can streamline the creation of
servlets.
The way you develop and deploy servlets differs among IDEs.
Furthermore, many readers will be using the command-line tools rather than an IDE.
Therefore, if you are using an IDE, you must refer to the instructions for that
environment for information concerning the development and deployment of servlets.
For this reason, the instructions given here and elsewhere in this chapter assume that only
the command-line tools are employed. Thus, they will work for nearly any reader.
As stated, this chapter uses Tomcat in the examples.
It provides a simple, yet effective way to experiment with servlets using only the
command line tools.
It is also widely available in various programming environments.
Furthermore, since only command-line tools are used, you don’t need to download and
install an IDE just to experiment with servlets.
Understand, however, that even if you are developing in an environment that uses a
different servlet container, the concepts presented here still apply.
It is just that the mechanics of preparing a servlet for testing will be slightly different.
You may need to set the environmental variable JAVA_HOME to the top-level
directory in which the Java Development Kit is installed.
NOTE All of the directories shown in this section assume Tomcat 10.0.7. If you install a
different version of Tomcat, then you will need to adjust the directory names and paths to
match those used by the version you installed.
Once installed, you start Tomcat by selecting startup.bat from the bin directly
under the apache-tomcat-10.0.7 directory.
To stop Tomcat, execute shutdown.bat, also in the bin directory.
The classes and interfaces needed to build servlets are contained in servlet-api.jar,
which is in the following directory:
C:\apache-tomcat-10.0.7\lib
To make servlet-api.jar accessible, update your CLASSPATH environment variable
so that it includes
C:\apache-tomcat-10.0.7\lib\ servlet-api.jar
Alternatively, you can specify this file when you compile the servlets. For example, the
following command compiles the first servlet example:
javac HelloServlet.java -classpath "C:\apache-tomcat-10.0.7\lib\servlet-api.jar”
Once you have compiled a servlet, you must enable Tomcat to find it. For our purposes,
this means putting it into a directory under Tomcat’s webapps directory and entering
its name into a web.xml file.
To keep things simple, the examples in this chapter use the directory and web.xml file
that Tomcat supplies for its own example servlets.
This way, you won’t have to create any files or directories just to experiment with the
sample servlets.
Here is the procedure that you will follow.
First, copy the servlet’s class file into the following directory:
C:\apache-tomcat-10.0.7\webapps\examples\WEB-INF\classes
Next, add the servlet’s name and mapping to the web.xml file in the following
directory:
C:\apache-tomcat-10.0.7\webapps\examples\WEB-INF
For instance, assuming the first example, called HelloServlet, you will add the following
lines in the section that defines the servlets:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
Next, you will add the following lines to the section that defines the servlet mappings:
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlets/servlet/HelloServlet</url-pattern>
</servlet-mapping>
Follow the same general procedure for all of the examples.
ServletResponse object. This enables the servlet to formulate a response for the
client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In
this program, the MIME type is text/html. This indicates that the browser should
interpret the content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream
is sent to the client as part of the HTTP response. Then println( ) is used to write some
simple HTML source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the proper Tomcat
directory as described in the previous section. Also, add HelloServlet to the web.xml file,
as described earlier.
2. Start Tomcat
Start Tomcat as explained earlier. Tomcat must be running before you try to execute a
servlet.
The following table summarizes the core classes that are provided in the jakarta.servlet
package:
2. ServletConfig Interface
The ServletConfig interface allows a servlet to obtain configuration data when it is
loaded.
The methods declared by this interface are summarized here:
Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml
file, as previously described. Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically
generated by the servlet.
The following table summarizes the classes used in this chapter. The most important of
these is HttpServlet. Servlet developers typically extend this class in order to process
HTTP requests.
The source code for ColorGetServlet.java is shown in the following listing. The doGet( )
method is overridden to process any HTTP GET requests that are sent to this servlet. It
uses the getParameter( ) method of HttpServletRequest to obtain the selection that was
made by the user. A response is then formulated.
Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml
file, as previously described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL
that is sent to the web server. Assume that the user selects the red option and submits the
form. The URL sent from the browser to the server is
http://localhost:8080/examples/servlets/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.
The HTML source code for ColorPost.html is shown in the following listing. It is
identical to ColorGet.html except that the method parameter for the form tag explicitly
specifies that the POST method should be used, and the action parameter for the form tag
specifies a different servlet.
The source code for ColorPostServlet.java is shown in the following listing. The doPost(
) method is overridden to process any HTTP POST requests that are sent to this servlet.
It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was
made by the user. A response is then formulated.
Compile the servlet and perform the same steps as described in the previous section to
test it.
NOTE Parameters for an HTTP POST request are not included as part of the URL that is
sent to the web server. In this example, the URL sent from the browser to the server is http://
localhost:8080/examples/servlets/servlet/ColorPostServlet. The parameter names and values
are sent in the body of the HTTP request.
The HTML source code for AddCookie.html is shown in the following listing. This page
contains a text field in which a value can be entered. There is also a submit button on the
page. When this button is pressed, the value in the text field is sent to AddCookieServlet
via an HTTP POST request.
The source code for AddCookieServlet.java is shown in the following listing. It gets
the value of the parameter named "data".
It then creates a Cookie object that has the name "MyCookie" and contains the value of
the "data" parameter.
The cookie is then added to the header of the HTTP response via the addCookie( )
method. A feedback message is then written to the browser.
The source code for GetCookiesServlet.java is shown in the following listing. It invokes
the getCookies( ) method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response. Observe
that the getName( ) and getValue( ) methods are called to obtain this information.
Compile the servlets. Next, copy them to the appropriate directory, and update the
web.xml file, as previously described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display AddCookie.html in a browser.
3. Enter a value for MyCookie.
4. Submit the web page.
After completing these steps, you will observe that a feedback message is displayed by
the browser.
Next, request the following URL via the browser:
http://localhost:8080/examples/servlets/servlet/GetCookiesServlet
Observe that the name and value of the cookie are displayed in the browser.
In this example, an expiration date is not explicitly assigned to the cookie via the
setMaxAge( ) method of Cookie. Therefore, the cookie expires when the browser session
ends. You can experiment by using setMaxAge( ) and observe that the cookie is then
saved on the client machine.
A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name "date" to this object.
When you first request this servlet, the browser displays one line with the current date
and time information. On subsequent invocations, two lines are displayed. The first line
shows the date and time when the servlet was last accessed. The second line shows the
current date and time.