2005 pearson education, inc. all rights reserved. 1 26 servlets
TRANSCRIPT
1
2005 Pearson Education, Inc. All rights reserved.
2626
Servlets
2
2005 Pearson Education, Inc. All rights reserved.
A fair request should be followed by the deed in silence.
— Dante Alighieri
The longest part of the journey is said to be the passing of the gate.
— Marcus Terentius Varro
If nominated, I will not accept; if elected, I will not serve.
— General William T. Sherman
Friends share all things.— Pythagoras
3
2005 Pearson Education, Inc. All rights reserved.
OBJECTIVES
In this chapter you will learn: How servlets can be used to extend a Web
server's functionality. The servlet life cycle. To execute servlets with the Apache
Tomcat server. To be able to respond to HTTP requests
from an HttpServlet. To be able to redirect requests to static
and dynamic Web resources. To use JDBC from a servlet.
4
2005 Pearson Education, Inc. All rights reserved.
26.1 Introduction
26.2 Servlet Overview and Architecture
26.2.1 Interface Servlet and the Servlet Life Cycle
26.2.2 HttpServlet Class
26.2.3 HttpServletRequest Interface
26.2.4 HttpServletResponse Interface
26.3 Setting Up the Apache Tomcat Server
26.4 Handling HTTP get Requests
26.4.1 Deploying a Web Application
26.5 Handling HTTP get Requests Containing Data
26.6 Handling HTTP post Requests
26.7 Redirecting Requests to Other Resources
26.8 Multitier Applications: Using JDBC from a Servlet
26.9 Welcome Files
26.10 Wrap-Up
26.11 Internet and Web Resources
5
2005 Pearson Education, Inc. All rights reserved.
26.1 Introduction
• Java networking capabilities– Socket-based and packet-based communications
• Package java.net
– Remote Method Invocation (RMI)• Package java.rmi
– Common Object Request Broker Architecture (COBRA)• Package org.omg
– Remote Method Invocation over the Internet Inter-Orb Protocol (RMI-IIOP)
6
2005 Pearson Education, Inc. All rights reserved.
26.1 Introduction (Cont.)
• Client-server relationship– Servlets and JavaServer Pages (JSP)
• Request-response model
• Packages javax.servlet
javax.servlet.http
javax.servlet.jsp
javax.servlet.tagext• Common implementation of request-response model
– Web browsers and Web servers
• Form the Web components of J2EE
7
2005 Pearson Education, Inc. All rights reserved.
26.1 Introduction (Cont.)
• Thin clients– Provide presentation
– Do not process data
– Require fewer computing resources
8
2005 Pearson Education, Inc. All rights reserved.
26.1 Introduction (Cont.)
• Apache Jakarta Project and the Tomcat Server
• Tomcat– Jakarta project
– Official reference implementation of the JSP and servlet standards
9
2005 Pearson Education, Inc. All rights reserved.
26.2 Servlet Overview and Architecture
• Servlet– Small portion of the content is static text or markup– Do not produce content– Perform a task on behalf of the client
• JavaServer Pages– Extension of servlet technology– Most of the content is static text or markup– Small portion of the content is generated dynamically
• Servlet container (servlet engine)– Server that executes a servlet
10
2005 Pearson Education, Inc. All rights reserved.
26.2 Servlet Overview and Architecture (Cont.)
• Web servers and application servers– Sun Java System Application Server
– Microsoft’s Internet Information Server (IIS)
– Apache HTTP Server
– BEA’s WebLogic Application Server
– IBM’s WebSphere Application Server
– World Wide Web Consortium’s Jigsaw Web Server
11
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.1 | Servlet architecture.
12
2005 Pearson Education, Inc. All rights reserved.
26.2.1 Interface Servlet and the Servlet Life Cycle
• Interface Servlet– All servlets must implement this interface– All methods of interface Servlet are invoked by servlet
container
• Servlet life cycle– Servlet container invokes the servlet’s init method– Servlet’s service method handles requests– Servlet’s destroy method releases servlet resources when the
servlet container terminates the servlet
• Servlet implementation– GenericServlet– HttpServlet
13
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 26.1
Servlets implement the Servlet interface of package javax.servlet.
14
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.2 | Servlet interface methods.
Method Description
void init( ServletConfig config ) The servlet container calls this method once during a servlet’s execution cycle to initialize the
servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet.
ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information, such as its initialization parameters and ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes).
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 servlet.
void destroy()
This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as open files or open database connections, should be deallocated here.
15
2005 Pearson Education, Inc. All rights reserved.
26.2.1 Interface Servlet and the Servlet Life Cycle (Cont.)
• Interface Servlet implementation– GenericServlet
• Abstract class
• Package javax.servlet• Protocol-independent servlet
– HttpServlet• Abstract class
• Package javax.servlet.http• Use the HTTP protocol to exchange information
• Key method service
– ServletRequest and ServletResponse
16
2005 Pearson Education, Inc. All rights reserved.
26.2.2 HttpServlet Class
• Overrides method service• Two most common HTTP request types
– get requests• Get/retrieve information from server
– post requests• Post/send data to server
• Method doGet responds to get requests• Method doPost responds to post requests•HttpServletRequest and HttpServletResponse objects
17
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.3 | HttpServlet class’s other methods.
Method Description
doDelete Called in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers because of its inherent security risks (e.g., the client could delete a file that is critical to the execution of the server or an application).
doHead Called in response to an HTTP head request. Such a request is normally used when the client wants only the response’s headers, such as its content type and content length. By overriding this method, the servlet does not compute the response body, thus improving performance.
doOptions Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the HTTP version (1.0 or 1.1) and the request methods the server supports.
doPut Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers because of its inherent security risks (e.g., the client could place an executable application on the server, which, if executed, could damage the server—perhaps by deleting critical files or occupying resources).
doTrace Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).
18
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 26.2
Do not override method service in an HttpServlet subclass. Doing so prevents the servlet from distinguishing between request types.
19
2005 Pearson Education, Inc. All rights reserved.
26.2.3 HttpServletRequest Interface
• Servlet container– creates an HttpServletRequest object
– passes it to the servlet’s service method
•HttpServletRequest object – contains the request from the client
– provides methods that enable the servlet to process the request
20
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.4 | HttpServletRequest methods.
Method Description
String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name.
Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request.
String[] getParameterValues( String name )
For a parameter with multiple values, this method returns an array of strings containing the values for a specified servlet parameter.
Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server. Cookie objects can be used to uniquely identify clients to the servlet.
HttpSession getSession( boolean create )
Returns an HttpSession object associated with the client’s current browsing session. This method can create an HttpSession object (true argument) if one does not already exist for the client. HttpSession objects and Cookies are used in similar ways for uniquely identifying clients.
String getLocalName()
Gets the host name on which the request was received.
String getLocalAddr()
Gets the Internet Protocol (IP) address on which the request was received.
int getLocalPort()
Gets the Internet Protocol (IP) port number on which the request was received.
21
2005 Pearson Education, Inc. All rights reserved.
26.2.4 HttpServletResponse Interface
• Servlet container – creates an HttpServletResponse object
– passes it to the servlet’s service method
•HttpServletResponse object – provides methods that enable the servlet to formulate the
response to the client
22
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.5 | HttpServletResponse methods.
Method Description
void addCookie( Cookie cookie ) Used to add a Cookie to the header of the response to the client. The Cookie’s
maximum age and whether Cookies are enabled on the client determine whether Cookies are stored on the client.
ServletOutputStream getOutputStream() Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter() Obtains a character-based output stream for sending text data (usually HTML formatted
text) to the client.
void setContentType( String type ) Specifies the content type of the response to the browser. The content type helps the
browser determine how to display the data (or possibly what other application to execute to process the data). The content type is also known as MIME (Multipurpose Internet Mail Extension) type of the data. For examples, content type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page; content type "image/gif" indicates that the response is an image, so the browser displays the image. For a complete list of content types, visit www.isi.edu/in-notes/iana/assignments/media-types/media-types.
String getContentType() Gets the content type of the response.
23
2005 Pearson Education, Inc. All rights reserved.
26.3 Setting Up the Apache Tomcat Server
• Download Tomcat (version 5.0.25)– apache.towardex.com/jakarta/tomcat-5/v5.0.25/bin
• Define environment variables– JAVA_HOME
• C:\Program Files\Java\jdk1.5.0
– CATALINA_HOME• C:\jakarta-tomcat-5.-.25
24
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 26.1
On some platforms you may need to restart your computer for the new environment variables to take effect
25
2005 Pearson Education, Inc. All rights reserved.
26.3 Setting Up the Apache Tomcat Server (Cont.)
• Start the Tomcat server– startup
• Launch the Tomcat server– http://localhost:8080/
• Shutdown the Tomcat server– shutdown
26
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.6 | Tomcat documentation home page. Copyright 2000-2004 The Apache Software Foundation (http://www.apache.org/). All rights reserved.
27
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 26.2
If the host name localhost does not work on your computer, substitute the IP address 127.0.0.1 instead.
28
2005 Pearson Education, Inc. All rights reserved.
26.4 Handling HTTP get Requests
•get request– Retrieve the content of a URL
• Example: WelcomeServlet – a servlet handles HTTP get requests
29
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet.java
(1 of 2)
Lines 3-6
Line 10
Lines 13-44
Line 17
Line 18
Line 23
1 // Fig. 26.7: WelcomeServlet.java
2 // A simple servlet to process get requests.
3 import javax.servlet.ServletException;
4 import javax.servlet.http.HttpServlet;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import java.io.IOException;
8 import java.io.PrintWriter;
9
10 public class WelcomeServlet extends HttpServlet
11 {
12 // process "get" requests from clients
13 protected void doGet( HttpServletRequest request,
14 HttpServletResponse response )
15 throws ServletException, IOException
16 {
17 response.setContentType( "text/html" );
18 PrintWriter out = response.getWriter();
19
20 // send XHTML page to client
21
22 // start XHTML document
23 out.println( "<?xml version = \"1.0\"?>" );
24
25 out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
26 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
27 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
28
29 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
30
Import the classes and interfaces in the javax.servlet and javax.servlet.http packages
Extends HttpServlet to handle HTTP get requests and HTTP post requests
Override method doGet to provide custom get request processing
Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client
Uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client
Create the XHTML document by writing strings with the out object’s println method
30
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet.java
(2 of 2)
Line 43
31 // head section of document
32 out.println( "<head>" );
33 out.println( "<title>A Simple Servlet Example</title>" );
34 out.println( "</head>" );
35
36 // body section of document
37 out.println( "<body>" );
38 out.println( "<h1>Welcome to Servlets!</h1>" );
39 out.println( "</body>" );
40
41 // end XHTML document
42 out.println( "</html>" );
43 out.close(); // close stream to complete the page
44 } // end method doGet
45 } // end class WelcomeServlet
Closes the output stream, flushes the output buffer and sends the information to the client
31
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet.html
(1 of 2)
Line 13
Line 13
Line 15
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 26.7: WelcomeServlet.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Handling an HTTP Get Request</title>
10 </head>
11
12 <body>
13 <form action = "/jhtp6/welcome1" method = "get">
14 <p><label>Click the button to invoke the servlet
15 <input type = "submit" value = "Get HTML Document" />
16 </label></p>
17 </form>
18 </body>
19 </html>
The form’s action attribute (/jhtp6/welcome1) specifies the URL path that invokes the servlet
The form’s method attribute indicates that the browser sends a get request to the server, which results a call to the servlet’s doGet method
Create a button, when clicked, the form’s action is performed
32
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet.html
(2 of 2)
Program output
33
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 26.3
The Tomcat documentation specifies how to integrate Tomcat with popular Web server applications such as the Apache HTTP Server and Microsoft’s IIS.
34
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 26.1
Using “servlet” or “servlets” as a context root may prevent a servlet from working correctly on some servers.
35
2005 Pearson Education, Inc. All rights reserved.
26.4.1 Deploying a Web Application
• Web applications– JSPs, servlets and their supporting files
• Deploying a Web application– Directory structure
• Context root
– Web application archive file (WAR file)
– Deployment descriptor• web.xml
36
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.9 | Web application standard directories.
Directory Description
context root This 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 this directory or its subdirectories. The name of this directory is specified by the Web application creator. To provide structure in a Web application, subdirectories can be placed in the context root. For example, if your application uses many images, you might place an images subdirectory in this directory. The examples of this chapter use jhtp6 as the context root.
WEB-INF This directory contains the Web application deployment descriptor (web.xml).
WEB-INF/classes This directory contains the servlet class files and other supporting class files used in a Web application. If the classes are part of a package, the complete package directory structure would begin here.
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR files can contain servlet class files and other supporting class files used in a Web application.
37
2005 Pearson Education, Inc. All rights reserved.
Outline
Web.xml
(1 of 2)
Lines 1-37
Lines 8-11
Lines 13-16
Lines 19-29
Line 20
Lines 22-24
Lines 26-28
1 <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
4 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
5 version="2.4">
6
7 <!-- General description of your Web application -->
8 <display-name>
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 </display-name>
12
13 <description>
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples.
16 </description>
17
18 <!-- Servlet definitions -->
19 <servlet>
20 <servlet-name>welcome1</servlet-name>
21
22 <description>
23 A simple servlet that handles an HTTP get request.
24 </description>
25
26 <servlet-class>
27 WelcomeServlet
28 </servlet-class>
29 </servlet>
30
Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet.
Element display-name specifies a name that can be displayed to the administrator of the server on which the Web application is installed.
Element description specifies a description of the Web application that might be displayed to the administrator of the server.
Element servlet describes a servlet.Element servlet-name is the name for the servlet.
Element description specifies a description for this particular servlet.
Element servlet-class specifies compiled servlet’s fully qualified class name.
38
2005 Pearson Education, Inc. All rights reserved.
Outline
Web.xml
(2 of 2)
Lines 32-35
Line 34
31 <!-- Servlet mappings -->
32 <servlet-mapping>
33 <servlet-name>welcome1</servlet-name>
34 <url-pattern>/welcome1</url-pattern>
35 </servlet-mapping>
36
37 </web-app>
Element servlet-mapping specifies servlet-name and url-pattern elements.Element url-pattern helps the server determine
which requests are sent to the servlet
39
2005 Pearson Education, Inc. All rights reserved.
26.4.1 Deploying a Web Application (Cont.)
• Invoke WelcomeServlet example– /jhtp6/welcome1
• /jhtp6 specifies the context root• /welcome1 specifies the URL pattern
• URL pattern formats– Exact match
• /jhtp5/welcome1
– Path mappings• /jhtp5/example/*
– Extension mappings• *.jsp
– Default servlet• /
40
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.11 | Web application directory and file structure for WelcomeServlet.
WelcomeServlet Web application directory and file structure
jhtp6 servlets WelcomeServlet.html WEB-INF web.xml classes WelcomeServlet.class
41
2005 Pearson Education, Inc. All rights reserved.
Common Programming Error 26.2
Not placing a servlet or other class files in the appropriate directory structure prevents the server from locating those classes properly. This results in an error response to the client Web browser.
42
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 26.3
You can test a servlet that handles HTTP get requests by typing the URL that invokes the servlet directly into your browser’s Address or Location field because get is the default HTTP method when browsing.
43
2005 Pearson Education, Inc. All rights reserved.
26.5 Handling HTTP get Requests Containing Data
• Servlet WelcomeServlet2– Responds to a get request that contains data
44
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet2.java
(1 of 2)
Line 17
1 // Fig. 26.12: WelcomeServlet2.java
2 // Processing HTTP get requests containing data.
3 import javax.servlet.ServletException;
4 import javax.servlet.http.HttpServlet;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import java.io.IOException;
8 import java.io.PrintWriter;
9
10 public class WelcomeServlet2 extends HttpServlet
11 {
12 // process "get" request from client
13 protected void doGet( HttpServletRequest request,
14 HttpServletResponse response )
15 throws ServletException, IOException
16 {
17 String firstName = request.getParameter( "firstname" );
18
19 response.setContentType( "text/html" );
20 PrintWriter out = response.getWriter();
21
22 // send XHTML document to client
23
24 // start XHTML document
25 out.println( "<?xml version = \"1.0\"?>" );
26
27 out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
28 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
29 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
The request object’s getParameter method receives the parameter name and returns the corresponding String value
45
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet2.java
(2 of 2)
Line 41
30
31 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
32
33 // head section of document
34 out.println( "<head>" );
35 out.println(
36 "<title>Processing get requests with data</title>" );
37 out.println( "</head>" );
38
39 // body section of document
40 out.println( "<body>" );
41 out.println( "<h1>Hello " + firstName + ",<br />" );
42 out.println( "Welcome to Servlets!</h1>" );
43 out.println( "</body>" );
44
45 // end XHTML document
46 out.println( "</html>" );
47 out.close(); // close stream to complete the page
48 } // end method doGet
49 } // end class WelcomeServlet2
Uses the result of line 17 as part of the response to the client
46
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet2.html
(1 of 2)
Line 16
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 26.13: WelcomeServlet2.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Processing get requests with data</title>
10 </head>
11
12 <body>
13 <form action = "/jhtp6/welcome2" method = "get">
14 <p><label>
15 Type your first name and press the Submit button
16 <br /><input type = "text" name = "firstname" />
17 <input type = "submit" value = "Submit" />
18 </p></label>
19 </form>
20 </body>
21 </html>
Get the first name from the user.
47
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet2.html
(2 of 2)
Program output
form data specified in URL’s query string as part of a get request
48
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.14 | Deployment descriptor information for servlet WelcomeServlet2.
Descriptor element Value
servlet element
servlet-name welcome2
description Handling HTTP get requests with data.
servlet-class WelcomeServlet2
servlet-mapping element
servlet-name welcome2
url-pattern /welcome2
49
2005 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 26.4
If an error occurs during the servlet invocation, the log files in the logs directory of the Tomcat installation can help you determine the error and debug the problem.
50
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 26.4
A get request is limited to standard characters, which means that you cannot submit any special characters via a get request. The length of the URL in a get request is limited. For example, the maximum URL length in Internet Explorer is 2,083 characters. Some Web servers might restrict this even more.
51
2005 Pearson Education, Inc. All rights reserved.
Good Programming Practice 26.1
A get request should not be used for sending sensitive data (e.g., a password) because the form data is placed in a query string that is appended to the request URL as plain text and can be intercepted.
52
2005 Pearson Education, Inc. All rights reserved.
26.6 Handling HTTP post Requests
• HTTP post request– Post data from an HTML form to a server-side form
handler
– Browsers cache Web pages
• Servlet WelcomeServlet3– Responds to a post request that contains data
53
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet3.java
(1 of 2)
Lines 13-48
Line 17
1 // Fig. 26.15: WelcomeServlet3.java
2 // Processing post requests containing data.
3 import javax.servlet.ServletException;
4 import javax.servlet.http.HttpServlet;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import java.io.IOException;
8 import java.io.PrintWriter;
9
10 public class WelcomeServlet3 extends HttpServlet
11 {
12 // process "post" request from client
13 protected void doPost( HttpServletRequest request,
14 HttpServletResponse response )
15 throws ServletException, IOException
16 {
17 String firstName = request.getParameter( "firstname" );
18
19 response.setContentType( "text/html" );
20 PrintWriter out = response.getWriter();
21
22 // send XHTML page to client
23
24 // start XHTML document
25 out.println( "<?xml version = \"1.0\"?>" );
26
27 out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
28 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
29 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
30
Declare a doPost method to responds to post requests
The request object’s getParameter method receives the parameter name and returns the corresponding String value
54
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet3.java
(2 of 2)
31 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
32
33 // head section of document
34 out.println( "<head>" );
35 out.println(
36 "<title>Processing post requests with data</title>" );
37 out.println( "</head>" );
38
39 // body section of document
40 out.println( "<body>" );
41 out.println( "<h1>Hello " + firstName + ",<br />" );
42 out.println( "Welcome to Servlets!</h1>" );
43 out.println( "</body>" );
44
45 // end XHTML document
46 out.println( "</html>" );
47 out.close(); // close stream to complete the page
48 } // end method doPost
49 } // end class WelcomeServlet3
55
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet3.html
(1 of 2)
Lines 13-19
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 26.16: WelcomeServlet3.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Handling an HTTP Post Request with Data</title>
10 </head>
11
12 <body>
13 <form action = "/jhtp6/welcome3" method = "post">
14 <p><label>
15 Type your first name and press the Submit button
16 <br /><input type = "text" name = "firstname" />
17 <input type = "submit" value = "Submit" />
18 </label></p>
19 </form>
20 </body>
21 </html>
Provide a form in which the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet3
56
2005 Pearson Education, Inc. All rights reserved.
Outline
WelcomeServlet3.html
(2 of 2)
Program output
57
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.17 | Deployment descriptor information for servlet WelcomeServlet3.
Descriptor element Value
servlet element
servlet-name welcome3
description Handling HTTP post requests with data.
servlet-class WelcomeServlet3
servlet-mapping element
servlet-name welcome3
url-pattern /welcome3
58
2005 Pearson Education, Inc. All rights reserved.
26.7 Redirecting Requests to Other Resources
• Servlet RedirectServlet– Redirects the request to a different resource
59
2005 Pearson Education, Inc. All rights reserved.
Outline
RedirectServlet.java
(1 of 2)
Line 17
Lines 21 and 23
Line 22
Line 24
1 // Fig. 26.18: RedirectServlet.java
2 // Redirecting a user to a different Web page.
3 import javax.servlet.ServletException;
4 import javax.servlet.http.HttpServlet;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 import java.io.IOException;
8 import java.io.PrintWriter;
9
10 public class RedirectServlet extends HttpServlet
11 {
12 // process "get" request from client
13 protected void doGet( HttpServletRequest request,
14 HttpServletResponse response )
15 throws ServletException, IOException
16 {
17 String location = request.getParameter( "page" );
18
19 if ( location != null )
20 {
21 if ( location.equals( "deitel" ) )
22 response.sendRedirect( "http://www.deitel.com" );
23 else if ( location.equals( "welcome1" ) )
24 response.sendRedirect( "welcome1" );
25 } // end if
26
27 // code that executes only if this servlet
28 // does not redirect the user to another page
29 response.setContentType( "text/html" );
30 PrintWriter out = response.getWriter();
Obtains the page parameter from the request.
Determine if the value is either “deitel” or “welcome1”Redirects the request to
www.deitel.com.Redirects the request to the servlet WelcomeServlet.
60
2005 Pearson Education, Inc. All rights reserved.
Outline
RedirectServlet.java
(2 of 2)
31
32 // start XHTML document
33 out.println( "<?xml version = \"1.0\"?>" );
34
35 out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
36 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
37 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
38
39 out.println(
40 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
41
42 // head section of document
43 out.println( "<head>" );
44 out.println( "<title>Invalid page</title>" );
45 out.println( "</head>" );
46
47 // body section of document
48 out.println( "<body>" );
49 out.println( "<h1>Invalid page requested</h1>" );
50 out.println( "<p><a href = " +
51 "\"servlets/RedirectServlet.html\">" );
52 out.println( "Click here to choose again</a></p>" );
53 out.println( "</body>" );
54
55 // end XHTML document
56 out.println( "</html>" );
57 out.close(); // close stream to complete the page
58 } // end method doGet
59 } // end class RedirectServlet
61
2005 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 26.5
Using relative paths to reference resources in the same context root makes your Web application more flexible. For example, you can change the context root without making changes to the static and dynamic resources in the application.
62
2005 Pearson Education, Inc. All rights reserved.
Outline
RedirectServlet.html
(1 of 2)
Lines 15-16 and 17-18
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 26.19: RedirectServlet.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Redirecting a Request to Another Site</title>
10 </head>
11
12 <body>
13 <p>Click a link to be redirected to the appropriate page</p>
14 <p>
15 <a href = "/jhtp6/redirect?page=deitel">
16 www.deitel.com</a><br />
17 <a href = "/jhtp6/redirect?page=welcome1">
18 Welcome servlet</a>
19 </p>
20 </body>
21 </html>
Provide links that allow the user to invoke the servlet RedirectServlet
63
2005 Pearson Education, Inc. All rights reserved.
Outline
RedirectServlet.html
(2 of 2)
Program output
64
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.20 | Deployment descriptor information for servlet RedirectServlet.
Descriptor element Value
servlet element
servlet-name redirect
description Redirecting to static Web pages and other servlets.
servlet-class RedirectServlet
servlet-mapping element
servlet-name redirect
url-pattern /redirect
65
2005 Pearson Education, Inc. All rights reserved.
26.8 Multitier Applications: Using JDBC from a Servlet
• Three-tier distributed applications– User interface
– Business logic
– Database
• Web servers often represent the middle tier
• Three-tier distributed application example– SurveyServlet
– Survey.html
– MySQL database
66
2005 Pearson Education, Inc. All rights reserved.
Outline
SurveyServlet.java
(1 of 6)
Lines 7-11
Line 21
Line 22
1 // Fig. 26.21: SurveyServlet.java
2 // A Web-based survey that uses JDBC from a servlet.
3 package com.deitel.jhtp6.servlets;
4
5 import java.io.PrintWriter;
6 import java.io.IOException;
7 import java.sql.Connection;
8 import java.sql.DriverManager;
9 import java.sql.Statement;
10 import java.sql.ResultSet;
11 import java.sql.SQLException;
12 import javax.servlet.ServletConfig;
13 import javax.servlet.ServletException;
14 import javax.servlet.UnavailableException;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18
19 public class SurveyServlet extends HttpServlet
20 {
21 private Connection connection;
22 private Statement statement;
23
Import interfaces and classes for database manipulation
Declare a Connection to manage the database connectionDeclare a Statement for updating the vote count, totaling all the votes and obtaining the complete survey result
67
2005 Pearson Education, Inc. All rights reserved.
Outline
SurveyServlet.java
(2 of 6)
Line 30
Lines 31-34
Line 37
24 // set up database connection and create SQL statement
25 public void init( ServletConfig config ) throws ServletException
26 {
27 // attempt database connection and create Statements
28 try
29 {
30 Class.forName( config.getInitParameter( "databaseDriver" ) );
31 connection = DriverManager.getConnection(
32 config.getInitParameter( "databaseName" ) );
33 config.getInitParameter( "username" ),
34 config.getInitParameter( "password" ) );
35
36 // create Statement to query database
37 statement = connection.createStatement();
38 } // end try
39 // for any exception throw an UnavailableException to
40 // indicate that the servlet is not currently available
41 catch ( Exception exception )
42 {
43 exception.printStackTrace();
44 throw new UnavailableException(exception.getMessage());
45 } // end catch
46 } // end method init
47
Loads the database driver, which is specified in the initialization parameter “databaseDriver”
Attempt to open a connection to the animalsurvey database, the database name, username and password are specified in the initialization parameters
Create Statement to query database.
68
2005 Pearson Education, Inc. All rights reserved.
Outline
SurveyServlet.java
(3 of 6)
Lines 71-72
48 // process survey response
49 protected void doPost( HttpServletRequest request,
50 HttpServletResponse response )
51 throws ServletException, IOException
52 {
53 // set up response to client
54 response.setContentType( "text/html" );
55 PrintWriter out = response.getWriter();
56
57 // start XHTML document
58 out.println( "<?xml version = \"1.0\"?>" );
59
60 out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
61 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
62 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
63
64 out.println(
65 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
66
67 // head section of document
68 out.println( "<head>" );
69
70 // read current survey response
71 int value =
72 Integer.parseInt( request.getParameter( "animal" ) );
73 String sql;
74
Obtain the survey response
69
2005 Pearson Education, Inc. All rights reserved.
Outline
SurveyServlet.java
(4 of 6)
Lines 79-80
Line 81
Line 84
Line 85
Lines 90-91
Line 92
75 // attempt to process a vote and display current results
76 try
77 {
78 // update total for current survey response
79 sql = "UPDATE surveyresults SET votes = votes + 1 " +
80 "WHERE id = " + value;
81 statement.executeUpdate( sql );
82
83 // get total of all survey responses
84 sql = "SELECT sum( votes ) FROM surveyresults";
85 ResultSet totalRS = statement.executeQuery( sql );
86 totalRS.next(); // position to first record
87 int total = totalRS.getInt( 1 );
88
89 // get results
90 sql = "SELECT surveyoption, votes, id FROM surveyresults " +
91 "ORDER BY id";
92 ResultSet resultsRS = statement.executeQuery( sql );
93 out.println( "<title>Thank you!</title>" );
94 out.println( "</head>" );
95
96 out.println( "<body>" );
97 out.println( "<p>Thank you for participating." );
98 out.println( "<br />Results:</p><pre>" );
99
Create sql to update total for current survey response
Execute sql statement to update total for current survey response
Create query to get total of all survey responsesExecute query to get total of
all survey responses
Create query to get survey results
Execute query to get survey results
70
2005 Pearson Education, Inc. All rights reserved.
Outline
SurveyServlet.java
(5 of 6)
Lines 103-111
Line 105
Line 107
100 // process results
101 int votes;
102
103 while ( resultsRS.next() )
104 {
105 out.print( resultsRS.getString( 1 ) );
106 out.print( ": " );
107 votes = resultsRS.getInt( 2 );
108 out.printf( "%.2f", ( double ) votes / total * 100 );
109 out.print( "% responses: " );
110 out.println( votes );
111 } // end while
112
113 resultsRS.close();
114
115 out.print( "Total responses: " );
116 out.print( total );
117
118 // end XHTML document
119 out.println( "</pre></body></html>" );
120 out.close();
121 } // end try
122 // if database exception occurs, return error page
123 catch ( SQLException sqlException )
124 {
125 sqlException.printStackTrace();
126 out.println( "<title>Error</title>" );
127 out.println( "</head>" );
128 out.println( "<body><p>Database error occurred. " );
129 out.println( "Try again later.</p></body></html>" );
Loop through all records in resultsRS
Obtain the value of the first column from the current record
Obtain the value of the second column from the current record
71
2005 Pearson Education, Inc. All rights reserved.
Outline
SurveyServlet.java
(6 of 6)
Lines 140-141
130 out.close();
131 } // end catch
132 } // end method doPost
133
134 // close SQL statements and database when servlet terminates
135 public void destroy()
136 {
137 // attempt to close statements and database connection
138 try
139 {
140 statement.close();
141 connection.close();
142 } // end try
143 // handle database exceptions by returning error to client
144 catch ( SQLException sqlException )
145 {
146 sqlException.printStackTrace();
147 } // end catch
148 } // end method destroy
149 } // end class SurveyServlet
Close Statement and database connection
72
2005 Pearson Education, Inc. All rights reserved.
Outline
Survey.html
(1 of 2)
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 26.22: Survey.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Survey</title>
10 </head>
11
12 <body>
13 <form method = "post" action = "/jhtp6/animalsurvey">
14 <p>What is your favorite pet?</p>
15 <p>
16 <input type = "radio" name = "animal"
17 value = "1" />Dog<br />
18 <input type = "radio" name = "animal"
19 value = "2" />Cat<br />
20 <input type = "radio" name = "animal"
21 value = "3" />Bird<br />
22 <input type = "radio" name = "animal"
23 value = "4" />Snake<br />
24 <input type = "radio" name = "animal"
25 value = "5" checked = "checked" />None
26 </p>
27 <p><input type = "submit" value = "Submit" /></p>
28 </form>
29 </body>
30 </html>
Provide a form in which the user can select an animal from a list of radio button, then click the Submit button to invoke animalsurvey
73
2005 Pearson Education, Inc. All rights reserved.
Outline
Survey.html
(2 of 2)
Program output
74
2005 Pearson Education, Inc. All rights reserved.
Fig. 26.23 | Deployment descriptor information for servlet SurveyServlet.
Descriptor element Value
servlet element
servlet-name animalsurvey
description Connecting to a database from a servlet.
servlet-class com.deitel.jhtp6.servlets.SurveyServlet
init-param
param-name databaseDriver
param-value com.mysql.jdbc.Driver
init-param
param-name databaseName
param-value jdbc:mysql://localhost/animalsurvey
init-param
param-name username
param-value jhtp6
init-param
param-name password
param-value jhtp6
servlet-mapping element
servlet-name animalsurvey
url-pattern /animalsurvey
75
2005 Pearson Education, Inc. All rights reserved.
26.9 Welcome Files
• Welcome files– Ordered list of files
• HTML, JSP documents
– Loaded when the request URL is not mapped to a servlet– Defined using the welcome-file-list element
• Contain one or more welcome-file elements– Specify the partial URL of a welcome file
• Without a leading or trailing /• E.g., specify index.html and index.htm as welcome files
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file></welcome-file-list>
76
2005 Pearson Education, Inc. All rights reserved.
Outline
index.html
(1 of 2)
Lines 15-24
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
4
5 <!-- Fig. 26.24: index.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Welcome File</title>
10 </head>
11
12 <body>
13 <p>Click a link to test each example demonstrated in this chapter</p>
14 <p>
15 <a href = "/jhtp6/servlets/WelcomeServlet.html">
16 WelcomeServlet</a><br />
17 <a href = "/jhtp6/servlets/WelcomeServlet2.html">
18 WelcomeServlet2</a><br />
19 <a href = "/jhtp6/servlets/WelcomeServlet3.html">
20 WelcomeServlet3</a><br />
21 <a href = "/jhtp6/servlets/RedirectServlet.html">
22 RedirectServlet</a><br />
23 <a href = "/jhtp6/servlets/Survey.html">
24 SurveyServlet</a><br />
25 </p>
26 </body>
27 </html>
Provide links to test all the examples demonstrated in this chapter
77
2005 Pearson Education, Inc. All rights reserved.
Outline
index.html
(2 of 2)
Program output