Professional Documents
Culture Documents
Outline 36.1 Introduction 36.2 Servlet Overview and Architecture 36.2.1 Interface Servlet and the Servlet Life Cycle 36.2.2 HttpServlet Class 36.2.3 HttpServletRequest Interface 36.2.4 HttpServletResponse Interface 36.3 Handling HTTP get Requests 36.3.1 Setting Up the Apache Tomcat Server 36.3.2 Deploying a Web Application 36.4 Handling HTTP get Requests Containing Data 36.5 Handling HTTP post Requests 36.6 Redirecting Requests to Other Resources 36.7 Multi-Tier Applications: Using JDBC from a Servlet 36.8 Web Resources
Tomcat
Jakarta project Official reference implementation of the JSP and servlet standards
36.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 implementation
GenericServlet HttpServlet
2004 Prentice Hall, Inc. All rights reserved.
The servlet container calls this method once during a servlets execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlets configuration information such as servlet initialization parameters and the servlets ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). This method is defined by a servlet programmer to return a string containing servlet information such as the servlets author and version.
ServletConfig getServletConfig()
String getServletInfo() void service( ServletRequest request, ServletResponse response ) void destroy()
The servlet container calls this method to respond to a client request to the servlet. This cleanup method is called when a 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.
Fig. 36.1
36.2.2 HttpServlet Class Overrides method service Two most common HTTP request types
get requests post requests
Method doGet responds to get requests Method doPost responds to post requests HttpServletRequest and HttpServletResponse objects
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.
Returns the names of all the parameters sent to the servlet as part of a post request.
For a parameter with multiple values, this method returns an array of strings containing the values for a specified servlet parameter. 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.
Fig. 36.3
Returns an HttpSession object associated with the clients current browsing session. This method can create an HttpSession object (true argument) if one does not already exist for the client. HttpSession objects are used in similar ways to Cookies for uniquely identifying clients. Some methods of interface HttpServletRequest.
Fig. 36.4
Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. Some methods of interface HttpServletResponse.
Example: WelcomeServlet
a servlet handles HTTP get requests
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Fig. 36.5: WelcomeServlet.java // A simple servlet to process get requests. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { // process "get" requests from clients protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" );
Outline
WelcomeServlet.java (1 of 2)
Extends HttpServlet to handle HTTP get requests and HTTP post requests. Override method doGet to provide custom get request processing. Uses the response objects Uses the responsemethod objectsto setContentType getWriter method toof obtain a to specify the content type the data reference PrintWriter be sent as to thethe response to the client. object that enables the servlet to send content to the client. Create the XHTML document by writing strings with the out objects println method.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 } } // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page // body section of document out.println( "<body>" ); out.println( "<h1>Welcome to Servlets!</h1>" ); out.println( "</body>" ); // head section of document out.println( "<head>" ); out.println( "<title>A Simple Servlet Example</title>" ); out.println( "</head>" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
Outline
WelcomeServlet.java (2 of 2)
Closes the output stream, flushes the output buffer and sends the information to the client.
1 2 3 4 5 6 7 8 9
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 36.6: WelcomeServlet.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Handling an HTTP Get Request</title>
Outline
WelcomeServlet.html (1 of 1)
10 </head> 11 12 <body> 13 14 15 16 17 18 19 </form> 20 </body> 21 </html> <p><label>Click the button to invoke the servlet <input type = "submit" value = "Get HTML Document" /> </label></p> <form action = "/iw3htp3/welcome1" method = "get">
Outline
Program output
36.3.1 Setting Up the Apache Tomcat Server Download Tomcat (version 4.1.27)
jakarta.apache.org/site/binindex.cgi
Fig. 36.7
1 2 3 4 5 6 7 8 9 10 11
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app>
Outline
web.xml (1 of 2)
Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. <!-- General description of your Web application --> Element display-name specifies <display-name> a name that can be displayed to the Internet World Wide Web How to Program JSP administrator of the server on which and Servlet Chapter Examples the Web application is installed.
</display-name> <description> This is the Web demonstrate our </description>
12 13 14 15 16 17 18 19 20 21 22 23 24 25 <description>
Element description specifies a description of the Web application application in which we that might be displayed to the JSP and Servlet examples. administrator of the server.
Element servlet describes a servlet. servlet-name Element is the name for the servlet. Element description specifies a description for that handles an HTTP get request. this particular servlet.
26 27 28 29 30 31 32 33 34 35 36
Outline
web.xml (2 of 2)
</servlet-mapping>
37 </web-app>
Path mappings
/iw3htp3/example/*
Extension mappings
*.jsp
Default servlet
/
2004 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Fig. 36.11: WelcomeServlet2.java // Processing HTTP get requests containing data. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet2 extends HttpServlet { // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML document to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" );
Outline
WelcomeServlet2 (1 of 2)
21 22 23 24
The request objects getParameter method receives the parameter name and returns the corresponding String value.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 } }
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Processing get requests with data</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page
Outline
WelcomeServlet2 (2 of 2)
1 2 3 4 5 6 7 8 9
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 36.12: WelcomeServlet2.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Processing get requests with data</title>
Outline
WelcomeServlet2 .html (1 of 1)
10 </head> 11 12 <body> 13 14 15 16 17 18 19 20 21 </form> 22 </body> 23 </html> <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </p></label> <form action = "/iw3htp3/welcome2" method = "get">
Outline
Program output
Servlet WelcomeServlet3
Responds to a post request that contains data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Fig. 36.14: WelcomeServlet3.java // Processing post requests containing data. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet3 extends HttpServlet { // process "post" request from client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" );
Outline
WelcomeServlet3 .java (1 of 2)
21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 } }
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Processing post requests with data</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page
Outline
WelcomeServlet3 .java (1 of 2)
1 2 3 4 5 6 7 8 9
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 36.15: WelcomeServlet3.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Handling an HTTP Post Request with Data</title>
Outline
WelcomeServlet3 .html (1 of 1)
10 </head> 11 12 <body> 13 14 15 16 17 18 19 20 21 </form> 22 </body> 23 </html> <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </label></p> <form action = "/iw3htp3/welcome3" method = "post">
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.
Outline
Program output
welcome3 Handling HTTP post requests with data. servlet-class WelcomeServlet3 servlet-mapping element servlet-name welcome3 url-pattern /welcome3 Fig. 36.16 Deployment descriptor information for servlet WelcomeServlet3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Fig. 36.17: RedirectServlet.java // Redirecting a user to a different Web page. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class RedirectServlet extends HttpServlet { // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String location = request.getParameter( "page" ); if ( location != null ) if ( location.equals( "deitel" ) ) response.sendRedirect( else
Outline
RedirectServlet.java (1 of 3)
16 17 18 19 20 21 22 23 24
Determine if the value is either deitel or welcome1 Redirects the request to "http://www.deitel.com" ); www.deitel.com. Redirects the request to the servlet WelcomeServlet.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// code that executes only if this servlet // does not redirect the user to another page response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Invalid page</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<h1>Invalid page requested</h1>" );
Outline
RedirectServlet.java (2 of 3) Output a Web page indicating that an invalid request was made if method sendRedirect is not called.
49 50 51 52 53 54 55 56 57 58 } }
out.println( "<p><a href = " + "\"servlets/RedirectServlet.html\">" ); out.println( "Click here to choose again</a></p>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page
Outline
RedirectServlet.java (3 of 3)
1 2 3 4 5 6 7 8 9
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 36.18: RedirectServlet.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Redirecting a Request to Another Site</title>
Outline
RedirectServlet.html (1 of 1)
10 </head> 11 12 <body> 13 14 15 16 17 18 19 <p>Click a link to be redirected to the appropriate page</p> <p> <a href = "/iw3htp3/redirect?page=deitel"> www.deitel.com</a><br /> <a href = "/iw3htp3/redirect?page=welcome1"> Welcome servlet</a> </p>
Provide hyperlinks that allow the user to invoke the servlet RedirectServlet.
20 </body> 21 </html>
Outline
Program output
36.7 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications
User interface Business logic Database access
Web servers often represent the middle tier Three-tier distributed application example
SurveyServlet Survey.html
MS Access database
1 2 3 4 5 6 7 8 9
// Fig. 36.20: SurveyServlet.java // A Web-based survey that uses JDBC from a servlet. package com.deitel.iw3htp3.servlets; import java.io.*; import java.text.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*;
Outline
SurveyServlet.java (1 of 6)
10 11 public class SurveyServlet extends HttpServlet { 12 13 14 15 16 17 18 19 20 21 22 23 private Connection connection; private Statement statement;
// set up database connection and create SQL statement public void init( ServletConfig config ) throws ServletException { // attempt database connection and create Statements try { connection = DriverManager.getConnection( config.getInitParameter( "databaseName" ) ); Class.forName( config.getInitParameter( "databaseDriver" ) );
Loads the database driver. Attempt to open a connection to the animalsurvey database.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 { } } }
Outline
SurveyServlet.java (2 of 6)
// for any exception throw an UnavailableException to // indicate that the servlet is not currently available catch ( Exception exception ) { exception.printStackTrace(); throw new UnavailableException(exception.getMessage());
// process survey response protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException // set up response to client response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); DecimalFormat twoDigits = new DecimalFormat( "0.00" ); // start XHTML document out.println( "<?xml version = \"1.0\"?>" );
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); // read current survey response int value = Integer.parseInt( request.getParameter( "animal" ) ); String query; // attempt to process a vote and display current results try { // update total for current survey response "WHERE id = " + value; statement.executeUpdate( query );
Outline
SurveyServlet.java (3 of 6)
Create query to update total for current survey response Execute query to update total for current survey response
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
// get total of all survey responses query = "SELECT sum( votes ) FROM surveyresults"; ResultSet totalRS = statement.executeQuery( query ); totalRS.next(); int total = totalRS.getInt( 1 ); // get results
Create query to get total of all Outline survey Execute responses query to get total of all survey responses SurveyServlet.java (4 of 6) Create query to get survey results Execute query to get survey results
query = "SELECT surveyoption, votes, id FROM surveyresults " + "ORDER BY id"; ResultSet resultsRS = statement.executeQuery( query ); out.println( "<title>Thank you!</title>" ); out.println( "</head>" ); out.println( "<body>" ); out.println( "<p>Thank you for participating." ); out.println( "<br />Results:</p><pre>" ); // process results int votes; while ( resultsRS.next() ) { out.print( resultsRS.getString( 1 ) ); out.print( ": " ); votes = resultsRS.getInt( 2 ); out.print( twoDigits.format( ( double ) votes / total * 100 ) );
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 } } }
out.print( "%
responses: " );
out.println( votes );
Outline
SurveyServlet.java (5 of 6)
resultsRS.close(); out.print( "Total responses: " ); out.print( total ); // end XHTML document out.println( "</pre></body></html>" ); out.close(); } // end try // if database exception occurs, return error page catch ( SQLException sqlException ) { sqlException.printStackTrace(); out.println( "<title>Error</title>" ); out.println( "</head>" ); out.println( "<body><p>Database error occurred. " ); out.println( "Try again later.</p></body></html>" ); out.close();
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 } // end class SurveyServlet } } // handle database exceptions by returning error to client catch ( SQLException sqlException ) { sqlException.printStackTrace(); } // close SQL statements and database when servlet terminates public void destroy() { // attempt to close statements try { statement.close(); connection.close();
Method destroy closes Statement and and database database connection. connection
Outline
SurveyServlet.java (6 of 6)
1 2 3 4 5 6 7 8 9
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 36.21: Survey.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Survey</title>
Outline
Survey.html (1 of 2)
10 </head> 11 12 <body> 13 <form method = "post" action = "/iw3htp3/animalsurvey"> 14 15 16 17 18 19 20 21 22 23 24 25 <p> <input type = "radio" name = "animal" value = "1" />Dog<br /> <input type = "radio" name = "animal" value = "2" />Cat<br /> <input type = "radio" name = "animal" value = "3" />Bird<br /> <input type = "radio" name = "animal" value = "4" />Snake<br /> <p>What is your favorite pet?</p>
26 27 28 29 30 31
<input type = "radio" name = "animal" value = "5" checked = "checked" />None </p> <p><input type = "submit" value = "Submit" /></p>
Outline
Survey.html (2 of 2)
Outline
Fig. 36.22