AhmadLang / Java, How To Program, 2004
.pdf
[Page 1274 (continued)]
26.11. Internet and Web Resources
This section lists a variety of servlet resources available on the Internet and provides a brief description of each.
java.sun.com/products/servlet/index.html
The servlet page at the Sun Microsystems, Java Web site provides access to the latest servlet information and servlet resources.
jakarta.apache.org
This is the Apache Project's home page for the Jakarta Project.
jakarta.apache.org/tomcat/index.html
Home page for the Tomcat servlets and JavaServer Pages reference implementation.
www.servlets.com
This Web site provides news, tools and documents for servlets and JSP technologies. It also links to the book Java Servlet Programming published by O'Reilly.
theserverside.com
TheServerSide.com is dedicated to information and resources for J2EE.
www.javacorporate.com/expresso/frame.jsp
Home of the open-source Expresso Framework, which includes a library of extensible servlet components to help speed Web application development.
www.servlet.com/srvdev.jhtml
ServletInc's Servlet Developers Forum provides resources for server-side Java developers and information about Web servers that support servlet technologies.
www.coolservlets.com
Provides free open-source Java servlets.
www.cetus-links.org/oo_java_servlets.html
Provides a list of links to resources on servlets and other technologies.
www.javaskyline.com
Java Skyline is an online magazine for servlet developers.
www.rfc-editor.org
The RFC Editor provides a search engine for RFCs (Requests for Comments). Many of these RFCs provide details of Web-related technologies. RFCs of interest to servlet developers include URI in WWW (RFC 1630), URI: generic syntax (RFC 2396), HTTP State Management Mechanism (RFC 2109), Use and Interpretation of HTTP Version Numbers (RFC 2145), Hyper Text Coffee Pot Control Protocol (RFC 2324), HTTP/1.1 (RFC 2616) and HTTP Authentication: Basic and Digest Authentication (RFC 2617).
[Page 1275]
Summary
The classes and interfaces used to define servlets are found in packages javax.servlet and javax.servlet.http.
URLs represent files or directories and can represent complex tasks, such as database lookups and Internet searches.
JavaServer Pages technology, an extension of servlet technology, simplifies the process of creating pages by separating presentation from content.
Servlets are normally executed by the servlet container component of a Web application server.
All servlets must implement the Servlet interface. The methods of interface Servlet are invoked automatically by the servlet container.
A servlet's life cycle begins when the servlet container loads the servlet into memorynormally in
response to the first request to that servlet. Before the servlet can handle the first request, the servlet container invokes the servlet's init method. After init completes execution, the servlet can respond to its first request. All requests are handled by a servlet's service method, which may be called many times during the servlet's life cycle. When the servlet container terminates the servlet, the servlet's destroy method is called to release servlet resources.
The key method in every servlet is method 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 and send data to the client. Commonly, this method should not be overridden.
Servlets typically extend class HttpServlet, which overrides method service to distinguish
between the typical requests received from a client Web browser. The two most common HTTP request types (also known as request methods) are get and post.
Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client, respectively.
Methods doGet and doPost receive as arguments an HttpServletRequest object and an HttpServletResponse object that enable interaction between the client and the server.
A response is sent to the client through a PrintWriter object returned by the getWriter method of the HttpServletResponse object.
The HttpServletResponse object's setContentType method specifies the content type of the response to the client. This enables the client browser to understand and handle the content.
The server localhost (IP address 127.0.0.1) is a well-known host name on computers that
support TCP/IP-based networking protocols such as HTTP. This host name can be used to test TCP/IP applications on the local computer.
The Tomcat server awaits requests from clients on port 8080. This port number must be specified as part of the URL to request a servlet running in Tomcat.
Tomcat is a fully functional implementation of the JSP and servlet standards. It includes a Web server, so it can be used as a standalone test container for JSPs and servlets.
JSPs, servlets and their supporting files are deployed as part of Web applications. In Tomcat, Web applications are deployed in the webapps subdirectory of the Tomcat installation.
A Web application has a well-known directory structure in which all the files that are part of the
application reside. This directory structure can be set up by the Tomcat server administrator in the webapps directory, or the entire directory structure can be archived in a Web application archive file (i.e., .war file).
WAR files are typically placed in the webapps directory. When the Tomcat server begins
execution, it extracts the contents of the WAR file into the appropriate webapps subdirectory structure.
[Page 1276]
The Web application directory structure is separated into a context rootthe top-level directory for
an entire Web applicationand several subdirectories. The context root is the root directory for the Web application.
All the JSPs, HTML documents, servlets and supporting files such as images and class files reside in the root directory or its subdirectories.
The WEB-INF directory contains the Web application deployment descriptor (web.xml), which is required to deploy a Web application.
The WEB-INF/classes directory contains the servlet class files and other supporting class files used in a Web application.
The WEB-INF/lib directory contains Java archive (JAR) files that may include servlet class files and other supporting class files used in a Web application.
Tomcat uses the directory names in the webapps subdirectory as the context names.
HTTP get requests can be typed directly into your browser's Address or Location field.
Parameters are passed as name-value pairs in a get request. A ? sepasrates the URL from the
data passed as part of a get request. Name-value pairs are passed with the name and the value separated by =. Two or more name-value pairs are separated by &.
Method getParameter of HttpServletRequest receives the parameter name as an argument and returns the corresponding String value, or null if the parameter is not part of the request.
An HTTP post request is often used to post data from a Web-page form to a server-side form
handler that processes the data. HTTP post requests are commonly used for passing sensitive data.
Method doPost receives the same two arguments as doGetan object that implements interface
HttpServletRequest to represent the client's request and an object that implements interface HttpServletResponse to represent the servlet's response.
Method sendRedirect of HttpServletResponse redirects a request to the specified URL.
When a servlet uses a relative path to reference another static or dynamic resource, the servlet assumes the same context root unless a complete URL is specified for the resource.
Once method sendRedirect executes, processing of the request by the servlet that called sendRedirect terminates.
When redirecting requests, the request parameters from the original request are passed as
parameters to the new request. Additional request parameters can also be passed. New parameters are added to the existing request parameters. If a new parameter has the same name as an existing parameter, the new parameter value takes precedence over the original value. However, all the values are still passed.
The complete set of values for a given request-parameter name can be obtained by calling
method getParameterValues of HttpServletRequest, which receives the parameter name as an argument and returns an array of Strings containing the parameter values in order from the most recently to the least recently added.
Many of today's applications are three-tier distributed applications, consisting of a user interface, business logic and database access.
In multitier architectures, Web servers are often used in the middle tier. Server-side
components, such as servlets, execute in an application server alongside the Web server. These components provide the business logic that manipulates data from databases and communicates with client Web browsers.
Servlet method init takes a ServletConfig argument, which provides the servlet with
information about its initialization parameters specified in a servlet element in the deployment descriptor. Each parameter appears in an init-param element with child elements param-name and param-value.
[Page 1277]
Web application developers can specify an ordered list of welcome files to be loaded when the request URL is not mapped to a servlet. These files are typically HTML or JSP documents.
Welcome files are defined using the welcome-file-list element in the deployment descriptor.
Element welcome-file-list contains one or more welcome-file elements. Each welcome-file element specifies the partial URL of a welcome file without a leading or trailing /.
[Page 1277 (continued)]
Terminology
Apache Tomcat server business logic
cache a Web page
CATALINA_HOME environment variable context root
deploy a Web application deployment descriptor destroy method of Servlet doGet method of HttpServlet
doPost method of HttpServlet GenericServlet class from javax.servlet
get request
getCookies method of HttpServletRequest getOutputStream method of HTTPServletResponse getParameter method of HttpServletRequest getParameterNames method of HttpServletRequest getParameterValues method of HttpServletRequest
getWriter method of HTTPServletResponse host name
HTTP header
HTTP (Hypertext Transfer Protocol)
HTTP request
HttpServlet interface
HttpServletRequest interface
HttpServletResponse interface
init method of Servlet
initialization parameter
Jakarta project
JAVA_HOME environment variable
javax.servlet package
javax.servlet.http package
localhost (127.0.0.1)
MIME type
port
post request
put request redirect a request request method request parameter
sendRedirect method of HttpServletResponse service method of Servlet
servlet
servlet container
Servlet interface servlet life cycle servlet mapping
ServletException class
ServletOutputStream class
ServletRequest interface
ServletResponse interface
setContentType method of HttpServletResponse text/html MIME type
thin client
three-tier distributed application trace request
URL pattern
WAR (Web application archive) file
Web application
Web application deployment descriptor (web.xml)
webapps directory
WEB-INF directory
WEB-INF/classes directory
WEB-INF/lib directory
welcome file
welcome-file element
welcome-file-list element
well-known port number
[Page 1277 (continued)]
Self-Review Exercises
26.1 Fill in the blanks in each of the following statements:
a.Classes HttpServlet and GenericServlet implement the__________interface.
b.Class HttpServlet defines the methods__________and__________to respond to get and post requests from a client.
[Page 1278]
c.HttpServletResponse method__________obtains a character-based output stream that enables text data to be sent to the client.
d.The form attribute__________specifies the server-side form handler , i.e., the program that handles the request.
e.__________is the well-known host name that refers to your own computer.
26.2 State whether each of the following is true or false. If false, explain why.
a.Servlets usually are used on the client side of a networking application.
b.Servlet methods are executed by the servlet container.
c.The two most common HTTP requests are get and put.
d.The well-known port number on a Web server where requests for HTML documents are made is 8080.
[Page 1278 (continued)]
Answers to Self-Review Exercises
26.1 a) Servlet. b) doGet, doPost. c) getWriter. d) action. e) localhost.
26.2 a. False. Servlets are usually used on the server side.
b.True.
c.False. The two most common HTTP request types are get and post. The put request type is often not allowed for security reasons.
d.False. The well-known port number on a Web server where requests for HTML documents are made is 80. Port 8080 is the Tomcat servlet container's default port.
[Page 1278 (continued)]
Exercises
26.3Create a servlet that displays the current date and time.
26.4Create a HTML form with three input fields: first name, last name and e-mail. Use the get method to pass these values to a servlet. Notice how data is attached to the URL. In the servlet, verify all input fields are non-null and display them back to the client.
26.5Create a Web application for dynamic FAQs. The application should obtain the information to create the dynamic FAQ Web page from a database that consists of a topics table and an faq table. The topics table has two fieldsa unique integer ID for each topic (topicID) and a name for each topic (topicName). The faq table has three fieldsthe topicID (a foreign key), a string representing the question (question) and the answer to the question (answer). When the servlet is invoked, it should read the data from the database and return a dynamically created Web page containing each question and answer, sorted by topic. [ Note: The examples folder for this chapter contains the SQL script faq.sql with which you can create the faq database for this example. For information on executing the SQL script, please refer to Chapter 25.] In the servlet's init method, create a CachedRowSet and set the database URL for the CachedRowSet. Sun's reference implementation of CachedRowSet is named
CachedRowSetImpl and is located in the package com.sun.rowset.
26.6Modify the Web application in Exercise 26.5 so that the initial request to the servlet returns a Web page of topics in the FAQ database. Then, the user can link to another servlet that returns only the frequently asked questions for a particular topic.
26.7Modify the Web application in Fig. 26.21 to allow the user to see the survey results without responding to the survey.
26.8Recall that the Web application in Fig. 26.21 implements a Web-based survey. Write a Web application that can be used generically with any survey of the appropriate formi.e., a question followed by a set of possible answers. Your Web application should have three servlets. The first is called to dynamically generate a list of survey names. When the user selects a survey, the second servlet should dynamically generate a form containing the survey options. When the user chooses an option, the third servlet should update the database and return the survey results. The survey database for this exercise has two tablessurveyCategory and surveyResult. Table surveyCategory has three fieldsa unique integer ID for each survey category (id), a string representing the survey name (name) and a string representing the survey question (question). Table surveyResult has three fieldsan integer ID (a foreign key) that identifies the survey category (id), a string representing the survey option (surveyOption) and an integer representing the total votes that option has received so far (voteCount). [Note: The examples folder for this chapter contains the SQL script survey.sql with which you can create the survey database for this example. For information on executing the SQL script, refer to Chapter 25. The sample database contains sample data for three surveysAnimals, Fruits and Sports.]
[Page 1279]
26.9Write a Web application that consists of a servlet (DirectoryServlet) and several Web documents. Document index.html should be the first document the user sees. In it, you should have a series of links for other Web pages in your site. When clicked, each link should invoke the servlet with a get request that contains a page parameter. The servlet should obtain parameter page and redirect the request to the appropriate document.
