Download presentation
Presentation is loading. Please wait.
Published byPauliina Helinä Laakso Modified over 6 years ago
1
Chapter 24: Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest Interface HttpServletResponse Interface Handling HTTP get Requests Setting Up the Apache Tomcat Server Deploying a Web Application Handling HTTP get Requests Containing Data Handling HTTP post Requests Redirecting Requests to Other Resources Multi-Tier Applications: Using JDBC from a Servlet Internet and World Wide Web Resources
2
Java networking capabilities
24.1 Introduction Java networking capabilities Socket-based and packet-based communications Package java.net Remote Method Invocation (RMI) Package java.rmi Servlets and Java Server Pages (JSP) Request-response model Packages javax.servlet javax.servlet.http javax.servlet.jsp javax.servlet.tagext Form the Web tier of J2EE
3
24.1 Introduction (Cont.) Servlets Tomcat Thin clients
Request/response mechanism redirection Tomcat Jakarta project Official reference implementation of the JSP and servlet standards
4
24.2 Servlet Overview and Architecture
Servlet container (servlet engine) Server that executes a servlet Web servers and application servers Sun ONE 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
5
24.2.1 Interface Servlet and the Servlet Life Cycle
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
6
24.2.1 Interface Servlet and the Servlet Life Cycle (Cont.)
7
Overrides method service Two most common HTTP request types
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
8
24.2.2 HttpServlet Class (Cont.)
9
24.2.3 HttpServletRequest Interface
Web server creates an HttpServletRequest object passes it to the servlet’s service method HttpServletRequest object contains the request from the client
10
24.2.3 HttpServletRequest Interface (Cont.)
11
24.2.4 HttpServletResponse Interface
Web server creates an HttpServletResponse object passes it to the servlet’s service method
12
24.2.4 HttpServletResponse Interface (Cont.)
13
24.3 Handling HTTP get Requests
Retrieve the content of a URL Example: WelcomeServlet a servlet handles HTTP get requests
14
Import the javax.servlet and javax.servlet.http packages.
// Fig. 24.5: WelcomeServlet.java // A simple servlet to process get requests. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class WelcomeServlet extends HttpServlet { 9 // process "get" requests from clients protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 17 // send XHTML page to client 19 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 22 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 26 Import the javax.servlet and javax.servlet.http packages. WelcomeServlet Lines 4-5 Line 8 Lines Line 15 Line 16 Lines 21-40 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.
15
27 out. println( "<html xmlns = \"http://www. w3
28 // head section of document out.println( "<head>" ); out.println( "<title>A Simple Servlet Example</title>" ); out.println( "</head>" ); 33 // body section of document out.println( "<body>" ); out.println( "<h1>Welcome to Servlets!</h1>" ); out.println( "</body>" ); 38 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 43 } WelcomeServlet Line 41 Closes the output stream, flushes the output buffer and sends the information to the client.
16
WelcomeServlet.html 1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig. 24.6: WelcomeServlet.html --> 6 <html xmlns = " <head> <title>Handling an HTTP Get Request</title> 10 </head> 11 12 <body> <form action = "/jhtp5/welcome1" method = "get"> 14 <p><label>Click the button to invoke the servlet <input type = "submit" value = "Get HTML Document" /> </label></p> 18 </form> 20 </body> 21 </html> WelcomeServlet.html
17
Program output
18
24.3.1 Setting Up the Apache Tomcat Server
Download Tomcat (version ) jakarta.apache.org/builds/ jakarta-tomcat-4.0/release/v4.1.12/bin/ Define environment variables JAVA_HOME CATALINA_HOME Start the Tomcat server startup.bat Connect to the Tomcat server using a Web browser
19
24.3.1 Setting Up the Apache Tomcat Server (Cont.).
Fig Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)
20
24.3.2 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
21
24.3.2 Deploying a Web Application (Cont.)
22
Element servlet describes a servlet.
<!DOCTYPE web-app PUBLIC \ "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" " 4 <web-app> 6 <!-- General description of your Web application --> <display-name> Java How to Program JSP and Servlet Chapter Examples </display-name> 12 <description> This is the Web application in which we demonstrate our JSP and Servlet examples. </description> 17 <!-- Servlet definitions --> <servlet> <servlet-name>welcome1</servlet-name> 21 <description> A simple servlet that handles an HTTP get request. </description> 25 web.xml Lines Lines Lines Lines Line 20 Lines Lines 26-28 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.
23
Element servlet-class specifies compiled servlet’s fully qualified class name.
WelcomeServlet </servlet-class> </servlet> 30 <!-- Servlet mappings --> <servlet-mapping> <servlet-name>welcome1</servlet-name> <url-pattern>/welcome1</url-pattern> </servlet-mapping> 36 37 </web-app> web.xml Lines Lines 32-35 Element servlet-mapping specifies servlet-name and url-pattern elements.
24
24.3.2 Deploying a Web Application (Cont.)
Invoke WelcomeServlet example /jhtp5/welcome1 /jhtp5 specifies the context root /welcome1 specifies the URL pattern URL pattern formats Exact match Path mappings /jhtp5/example/* Extension mappings *.jsp Default servlet /
25
24.3.2 Deploying a Web Application (Cont.)
26
24.4 Handling HTTP get Requests Containing Data
Servlet WelcomeServlet2 Responds to a get request that contains data
27
WelcomeServlet2 responds to a get request that contains data. Line 15
// Fig : WelcomeServlet2.java // Processing HTTP get requests containing data. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class WelcomeServlet2 extends HttpServlet { 9 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); 16 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 19 // send XHTML document to client 21 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 24 WelcomeServlet2 responds to a get request that contains data. Line 15 The request object’s getParameter method receives the parameter name and returns the corresponding String value.
28
WelcomeServlet2 responds to a get request that contains data. Line 39
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 28 out.println( "<html xmlns = \" ); 30 // head section of document out.println( "<head>" ); out.println( "<title>Processing get requests with data</title>" ); out.println( "</head>" ); 36 // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); 42 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 47 } WelcomeServlet2 responds to a get request that contains data. Line 39 Uses the result of line 16 as part of the response to the client.
29
Get the first name from the user.
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig : WelcomeServlet2.html --> 6 <html xmlns = " <head> <title>Processing get requests with data</title> 10 </head> 11 12 <body> <form action = "/jhtp5/welcome2" method = "get"> 14 <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </p></label> 20 </form> 22 </body> 23 </html> HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Line 17 Get the first name from the user.
30
HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Program output
31
24.4 Handling HTTP get Requests Containing Data (Cont.)
32
24.5 Handling HTTP post Requests
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
33
Declare a doPost method to responds to post requests.
// Fig : WelcomeServlet3.java // Processing post requests containing data. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class WelcomeServlet3 extends HttpServlet { 9 // process "post" request from client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); 16 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 19 // send XHTML page to client 21 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 24 WelcomeServlet3 responds to a post request that contains data. Lines 11-46 Declare a doPost method to responds to post requests.
34
25 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 28 out.println( "<html xmlns = \" ); 30 // head section of document out.println( "<head>" ); out.println( "<title>Processing post requests with data</title>" ); out.println( "</head>" ); 36 // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); 42 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 47 } WelcomeServlet3.java
35
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig : WelcomeServlet3.html --> 6 <html xmlns = " <head> <title>Handling an HTTP Post Request with Data</title> 10 </head> 11 12 <body> <form action = "/jhtp5/welcome3" method = "post"> 14 <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </label></p> 20 </form> 22 </body> 23 </html> HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Lines 13-21 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.
36
HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Program output
37
24.5 Handling HTTP post Requests (Cont.)
38
24.6 Redirecting Requests to Other Resources
Servlet RedirectServlet Redirects the request to a different resource
39
Obtains the page parameter from the request.
// Fig : RedirectServlet.java // Redirecting a user to a different Web page. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class RedirectServlet extends HttpServlet { 9 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String location = request.getParameter( "page" ); 16 if ( location != null ) 18 if ( location.equals( "deitel" ) ) response.sendRedirect( " ); else if ( location.equals( "welcome1" ) ) response.sendRedirect( "welcome1" ); 24 RedirectServletredirecting requests to other resources. Line 15 Lines Line 20 Line 23 Lines 29-56 Obtains the page parameter from the request. Determine if the value is either “deitel” or “welcome1” Redirects the request to Redirects the request to the servlet WelcomeServlet.
40
RedirectServletredirecting requests to other resources. Lines 28-55
// code that executes only if this servlet // does not redirect the user to another page 27 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 30 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 33 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 37 out.println( "<html xmlns = \" ); 40 // head section of document out.println( "<head>" ); out.println( "<title>Invalid page</title>" ); out.println( "</head>" ); 45 // body section of document out.println( "<body>" ); out.println( "<h1>Invalid page requested</h1>" ); Output a Web page indicating that an invalid request was made if method sendRedirect is not called. RedirectServletredirecting requests to other resources. Lines 28-55
41
RedirectServletredirecting requests to other resources.
out.println( "<p><a href = " + "\"servlets/RedirectServlet.html\">" ); out.println( "Click here to choose again</a></p>" ); out.println( "</body>" ); 53 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 58 } RedirectServletredirecting requests to other resources.
42
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig : RedirectServlet.html --> 6 <html xmlns = " <head> <title>Redirecting a Request to Another Site</title> 10 </head> 11 12 <body> <p>Click a link to be redirected to the appropriate page</p> <p> <a href = "/jhtp5/redirect?page=deitel"> /> <a href = "/jhtp5/redirect?page=welcome1"> Welcome servlet</a> </p> 20 </body> 21 </html> RedirectServlet.html document to demonstrate redirecting requests to other resources. Lines Lines 17-18 Provide hyperlinks that allow the user to invoke the servlet RedirectServlet.
43
RedirectServlet.html document to demonstrate redirecting requests to other resources. Program output
44
24.6 Redirecting Requests to other Resources (Cont.)
45
24.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 Cloudscape database
46
Servlets are initialized by overriding method init.
// Fig. 24.20: SurveyServlet.java // A Web-based survey that uses JDBC from a servlet. package com.deitel.jhtp5.servlets; 4 import java.io.*; import java.text.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; 10 11 public class SurveyServlet extends HttpServlet { private Connection connection; private Statement statement; 14 // set up database connection and create SQL statement public void init( ServletConfig config ) throws ServletException { // attempt database connection and create Statements try { System.setProperty( "db2j.system.home", config.getInitParameter( "databaseLocation" ) ); 22 Class.forName( config.getInitParameter( "databaseDriver" ) ); connection = DriverManager.getConnection( config.getInitParameter( "databaseName" ) ); SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Lines Lines Line 23 Lines Lines 27-31 Servlets are initialized by overriding method init. Specify database location Loads the database driver. Attempt to open a connection to the animalsurvey database.
47
Create Statement to query database.
26 // create Statement to query database statement = connection.createStatement(); } 30 // 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()); } 37 } // end of init method 39 // 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" ); 49 Create Statement to query database. SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Line 28
48
Obtain the survey response
// start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 52 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 56 out.println( "<html xmlns = \" ); 59 // head section of document out.println( "<head>" ); 62 // read current survey response int value = Integer.parseInt( request.getParameter( "animal" ) ); String query; 67 // attempt to process a vote and display current results try { 70 // update total for current surevy response query = "UPDATE surveyresults SET votes = votes + 1 " + "WHERE id = " + value; statement.executeUpdate( query ); 75 SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Lines Lines Line 74 Obtain the survey response Create query to update total for current survey response Execute query to update total for current survey response
49
Create query to get total of all survey responses
query = "SELECT sum( votes ) FROM surveyresults"; ResultSet totalRS = statement.executeQuery( query ); totalRS.next(); int total = totalRS.getInt( 1 ); 81 // get 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>" ); 88 out.println( "<body>" ); out.println( "<p>Thank you for participating." ); out.println( "<br />Results:</p><pre>" ); 92 // process results int votes; 95 while ( resultsRS.next() ) { out.print( resultsRS.getString( 1 ) ); out.print( ": " ); votes = resultsRS.getInt( 2 ); out.print( twoDigits.format( ( double ) votes / total * 100 ) ); out.print( "% responses: " ); out.println( votes ); } Create query to get total of all survey responses Execute query to get total of all survey responses SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Line 77 Line 78 Lines Line 85 Create query to get survey results Execute query to get survey results
50
105 resultsRS.close(); 107 out.print( "Total responses: " ); out.print( total ); 110 // end XHTML document out.println( "</pre></body></html>" ); out.close(); 114 } // end try 116 // 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(); } 126 } // end of doPost method 128 SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC.
51
Method destroy closes Statement and database connection.
// close SQL statements and database when servlet terminates public void destroy() { // attempt to close statements and database connection try { statement.close(); connection.close(); } 137 // handle database exceptions by returning error to client catch ( SQLException sqlException ) { sqlException.printStackTrace(); } } 143 144 } // end class SurveyServlet Method destroy closes Statement and database connection. SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Lines
52
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig. 24.21: Survey.html --> 6 <html xmlns = " <head> <title>Survey</title> 10 </head> 11 12 <body> 13 <form method = "post" action = "/jhtp5/animalsurvey"> 14 <p>What is your favorite pet?</p> 16 Survey.html document that allows users to submit survey responses to SurveyServlet.
53
<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 /> <input type = "radio" name = "animal" value = "5" checked = "checked" />None </p> 29 <p><input type = "submit" value = "Submit" /></p> 31 32 </form> 33 </body> 34 </html> Survey.html document that allows users to submit survey responses to SurveyServlet.
54
Survey.html document that allows users to submit survey responses to SurveyServlet.
55
24.7 Multi-Tier Applications: Using JDBC from a Servlet (Cont.)
56
24.8 Internet and World Wide Web Resources
Servlet resources java.sun.com/products/servlet/index.html
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.