Getting Started with Servlets
by Dr. Wenjie He
Introduction to Java Servlets
The Java
Servlet API allows a software developer to add dynamic content
to a Web server using the Java platform. A servlet extends the functionality of
a server. Servlets implement the request-response model of communication and
provide the foundation of the Java EE technologies.
1. Java Networking Levels
Java has three networking levels. The higher the level, the more abstraction on the networking
implementation details.
- Fundamental level
The package java.net provides the fundamental networking capabilities, through which
Java offers socket-based communications and packet-based communications.
The socket-based communications enable applications to view networking as streams of data -
a program can read a socket or write to a socket as simply as reading from a
file ot writing to a file.
The packet-based communications enable individual packets of information to be
transmitted - commonly used to transmit audio and video over the Internet.
- Higher-level
The java.rmi packages provide higher-level views of networking using the
Remote Method Invocation (RMI) technology. The RMI packages allow Java objects
running on separate Java Virtual Machines to communicate via remote method calls.
- Highest-level
The servlets provide the highest-level views of networking in Java. Packages
javax.servlet and javax.servlet.http offer the classes and
interfaces to dfine servlets. Servlets are effective for developing web-based
solutions that help provide secure access to a web site, interact with databases
on behalf of a client, dynamically generate custom XHTML documents to be displayed
by browsers and maintain unique session information for each client.
2. Interface Servlet
Architectually, all servlets must implement the
Servlet interface. The methods
of interface
Servlet are invoked automatically by the servlet container. This
interface defines five methods:
- void init( ServletConfig config)
The ServletConfig argument is supplied by the servlet container.
- ServletConfig getServletConfig()
The ServletConfig object provides access to the servlet's configuration information
such as servlet initiallization parameters and the servlet's ServletContext,
which provides the servlet with access to its environment.
- String getServletInfo()
This method is defined by a servlet programmer to return a String containing
servlet information such as the servlet's author and version.
- void service( ServletRequest request, ServletResponse response )
The servlet container calls this method to respond to a client request to the server.
- void destroy()
This cleanup method is called when the servlet is terminated by its servlet container.
Resources used by the servlet, such as an open file or an open database connection,
should be deallocated here.
3. Servlet Life Cycle
The life cycle of a servlet is controlled by the servlet container. When a request is mapped
to a servlet through its URL, the container performs the following steps.
- If an instance of the servlet does not exist, the web container
- Loads the servlet class.
In response to the first servlet request, the servlet container loads the servlet into memory.
- Creates an instance of the servlet class.
- Initializes the servlet instance by calling the init method.
- Invokes the service method
- After init completes execution, the servlet can respond to its first request.
- All requests are handled by a servlet's service method, which receives the
request, processes the request and sends a response to the client.
- During a servlet's life cycle, method service is called once per request.
Each new request typically results in a new thread of execution in which the
service method executes.
- When the servlet container terminates the servlet, the servlet's destroy method
is called to release servlet resources.
Servlet Case Study
In this section, we study the
Duke2 example.
1. Servlet Configuration
The servlets of a web application are configured in the
web.xml file. Let us look at the
web.xml of
Duke2.
Code Listing:
Duke2\WEB-INF\web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6.
7. <display-name>Duke2</display-name>
8.
9. <servlet>
10. <display-name>GreetingServlet</display-name>
11. <servlet-name>GreetingServlet</servlet-name>
12. <servlet-class>servlets.GreetingServlet</servlet-class>
13. </servlet>
14. <servlet>
15. <display-name>ResponseServlet</display-name>
16. <servlet-name>ResponseServlet</servlet-name>
17. <servlet-class>servlets.ResponseServlet</servlet-class>
18. </servlet>
19. <servlet-mapping>
20. <servlet-name>GreetingServlet</servlet-name>
21. <url-pattern>/greeting</url-pattern>
22. </servlet-mapping>
23. <servlet-mapping>
24. <servlet-name>ResponseServlet</servlet-name>
25. <url-pattern>/response</url-pattern>
26. </servlet-mapping>
27. </web-app>
- Element display-name (line 7, 10, 15) specifies a name that can be displayed
to the administrator of the server.
- Element servlet (line 9-13) describe a servlet.
- Element servlet-name (line 11) is the name of the servlet (its alias). In this
way, the original full path of the servlet class is hidden.
- Element servlet-class (line 12) specifies compiled servlet's fully qualified
class name.
- Element servlet-mapping (line 19-22) specifies servlet-name and
url-pattern elements.
- Element url-pattern (line 21) helps the server to determine which servlet
to send the requests. In this example, when the client visits the URL
http://localhost:8080/Duke2/greeting, the request will be sent to the
GreetingServlet.
2. Welcome file index.jsp
Code Listing:
Duke2\index.jsp
1. <jsp:forward page="/greeting"/>
- Since the welcome file is not configured explicitly in the web.xml,
the server takes the index.jsp as the welcome file by default.
- The <jsp:forward/> action:
Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP's execution.
- Action <jsp:forward/> has only a page attribute that
specifies the relative URI of the resource (of the same web application) to
which the request should be forwarded. In this example, the page attribute
refers to the relative URI of a servlet.
- When using the <jsp:forward/> action, the resource to
which the request will be forwarded must be in the same context (web application)
as the JSP that originally received the request.
3. Servlet Source Code
Code Listing:
GreetingServlet.java
1. package servlets;
2.
3. import java.io.*;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6.
7. /**
8. * This is a simple example of an HTTP Servlet. It responds to the GET
9. * method of the HTTP protocol.
10. */
11. public class GreetingServlet extends HttpServlet {
12. private static final long serialVersionUID = 6723471178342776147L;
13.
14. public void doGet(
15. HttpServletRequest request,
16. HttpServletResponse response) throws ServletException, IOException {
17. response.setContentType("text/html");
18. response.setBufferSize(8192);
19.
20. PrintWriter out = response.getWriter();
21.
22. // then write the data of the response
23. out.println("<html>" + "<head><title>Hello</title></head>");
24.
25. // then write the data of the response
26. out.println(
27. "<body bgcolor=\"#ffffff\">"
28. + "<img src=\"duke.waving.gif\" alt=\"Duke waving\">"
29. + "<h2>Hello, my name is Duke. What's yours?</h2>"
30. + "<form method=\"get\">"
31. + "<input type=\"text\" name=\"username\" size=\"25\">"
32. + "<p></p>" + "<input type=\"submit\" value=\"Submit\">"
33. + "<input type=\"reset\" value=\"Reset\">" + "</form>");
34.
35. String username = request.getParameter("username");
36.
37. if ((username != null) && (username.length() > 0)) {
38. RequestDispatcher dispatcher = getServletContext()
39. .getRequestDispatcher("/response");
40.
41. if (dispatcher != null) {
42. dispatcher.include(request, response);
43. }
44. }
45.
46. out.println("</body></html>");
47. out.close();
48. }
49.
50. public String getServletInfo() {
51. return "The Hello servlet says hello.";
52. }
53. }
- This servlets extends HTTPServlet, which defines enhanced processing
capabilities for servlets that extend the functionality of a web server.
- The key method in every servlet is service, which receives both a
ServletRequest object and a ServletResponse object. These
objects provide access to input and output streams that allow the servlet
to read data from the client and send data to client.
- If problems occur during the execution of a servlet, either ServletExceptions
or IOExceptions are thrown to indicate the problems.
- Web-based servlets typically extend class HTTPServlet. Class HTTPServlet
overrides method service to distinguish between the typical requests received
from a client wen browser.
- Line 12 is only used to stop an Eclipse warning.
- The two most common HTTP request types are get and post.
- A get request gets (or retrieves) information from a server. Common uses of
get requests are to retrieve an HTML document or an image.
- A post request posts (or sends) sends data to a server. Common uses of
post requests typically send information, such as authentication information
or data from a form that obtains user input, to a server.
- Class HTTPServlet defines methods doGet and doPost to response
to get and post requests from a client, respectively. These methods are
called by the service method, which is called when a request arrives at the server.
Method service first determines the request type, then calls the appropriate
method for handling such a request.
- Methods doGet and doPost receive as arguments an HttpServletRequest
object and HttpServletResponse object that enable interaction between the client
and server. The methods of HttpServletRequest make it easy to access the data
supplied as part of the request. The HttpServletResponse methods make it easy
to return the servlet's results to the web client.
- Every call to doGet or doPost for an HttpServlet receives an object
that implements interface HttpServletRequest. The web server that executes the
servlet creates an HttpServletRequest object and passes this to the servlet's
service method (which, in turn, passes it to doGet or doPost).
This object obtains the request from the client.
- Every call to doGet or doPost for an HttpServlet receives an object
that implements interface HttpServletResponse. The web server that executes the
servlet creates an HttpServletResponse object and passes this to the servlet's
service method (which, in turn, passes it to doGet or doPost).
This object provides a variety of methods that enable the servlet to formulate the response
to the client.
- Line 17 uses the response object's setContentType method to specify the
content type of the date to be sent as the response to the client.
- Line 20 uses the response object's getWriter method to obtain a reference
to the PrintWriter object that enables the servlet to send text content to the
client.
- Line 26-33 create the XHTML document by writing strings with the out object's
println method.
- Line 47 closes the output stream, flushes the output buffer and sends the information
to the client. This commits the response to the client.
- Parameters are passed as name/value pairs in a get request. The request
object's getParameter method receives the parameter name as an argument and
returns the corresponding String value, or null if the parameter is missing.
- In a servlet, you obtain the web application's servlet context by calling the
getServletContext method of the servlet itself. The ServletContext object
is returned in line 38.
- ServletContext method getRequestDispatcher receives the URL of the of
a servlet as an argument, then searches the ServletContext for a servlet by that URL.
(See line 39.)
- The interface RequestDispatcher defines an object that receives requests from the
client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
The servlet container creates the RequestDispatcher object, which is used as a wrapper
around a server resource located at a particular path or given by a particular name. (See line 39.)
- A RequestDispatcher object provides two methods - forward and include
- that enable a servlet to forward a client request to another resource or include content
from another resource in a servlet's response. In this example, we use the second method (line 42).
- Methods forward and include each takes two arguments - the
HttpServletRequest and HttpServletResponse objects for the current request.
Code Listing:
ResponseServlet.java
1. package servlets;
2.
3. import java.io.*;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6.
7. /**
8. * This is a simple example of an HTTP Servlet. It responds to the GET
9. * method of the HTTP protocol.
10. */
11. public class ResponseServlet extends HttpServlet {
12. private static final long serialVersionUID = 6723471178342776147L;
13.
14. public void doGet(
15. HttpServletRequest request,
16. HttpServletResponse response) throws ServletException, IOException {
17. PrintWriter out = response.getWriter();
18.
19. // then write the data of the response
20. String username = request.getParameter("username");
21.
22. if ((username != null) && (username.length() > 0)) {
23. out.println("<h2>Hello, " + username + "!</h2>");
24. }
25. }
26.
27. public String getServletInfo() {
28. return "The Response servlet says hello.";
29. }
30. }
This example can be easily understood by the explanation of the code
GreetingServlet.java above.
==========The End==========