Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and Architecture 30.2.1 Interface Servlet and the Servlet Life Cycle 30.2.2 HttpServlet Class 30.2.3 HttpServletRequest Interface 30.2.4 HttpServletResponse Interface 30.3 Handling HTTP get Requests 30.3.1 Setting Up the Apache Tomcat Server 30.3.2 Deploying a Web Application 30.4 Handling HTTP get Requests Containing Data 30.5 Handling HTTP post Requests 30.6 Redirecting Requests to Other Resources 30.7 Session Tracking 30.7.1 Cookies 30.7.2 Session Tracking with HttpSession 30.8 Multi-tier Applications: Using JDBC from a Servlet 30.9 HttpUtils Class 30.10 Internet and World Wide Web Resources
30.1 Introduction Java Networking Fundamental capabilities Network connections are sockets Contained in package java.net Higher-level packages Java.rmi (Remote Method Invocation classes) Allows JVMs to communicate via remote method calls Based on capabilities of package java.net Org.omg (Contains CORBA classes) Allows any two CORBA enabled applications to communicate.
Client-Server Relationship 30.1 Introduction Client-Server Relationship Client sends request, server responds Common implemetation – comunication between Web Server and Web Browser
30.1 Introduction Servlets Extend server functionality Often used with Web Servers To generate dynamic XHTML To provide secure access To interact with a database Packages javax.servlet, javax.servlet.http Provide classes and interfaces for servlets
30.2 Servlet Overview and Architecture Hypertext Transfer Protocol Basis to World Wide Web Communication Uses URIs (Uniform Resource Identifiers) URIs locate resources on internet
30.2 Servlet Overview and Architecture Servlet Containers (Servlet Engines) Provide servlet runtime environment Manage servlet lifecycle Incorporated in many popular web servers Microsoft Internet Information Server (IIS) Apache HTTP Server Many more Redirects HTTP requests to appropriate servlet
30.2.1 Interface Servlet and the Servlet Life Cycle In package javax.servlet Must be implemented by all servlets Servlet methods automatically invoked by servlet container
30.2.1 Interface Servlet and the Servlet Life Cycle
30.2.1 Interface Servlet and the Servlet Life Cycle Servlet Container Manages Life Cycle Invokes method init when servlet is initially loaded Usually in response to its first request Invokes method service to handle request Servlet processes request Obtains request from ServletRequest object Servlet responds to client Writes to ServletResponse object Called once per request Invokes method destroy to terminate servlet Releases servlet resources
30.2.1 Interface Servlet and the Servlet Life Cycle Servlet Abstract Implementations Provide default Servlet implementations GenericServlet Package javax.servlet Used in non-web servlets HttpServlet Package javax.servlet.http Used for Web-based servlets Defines enhanced Web processing capabilities
30.2.2 HttpServlet Class Class HttpServlet Overrides method service Differentiates between HTTP get and post requests Defines methods doGet and doPost to process requests Receives HttpServletRequest and HttpServletResponse objects
30.2.2 HttpServlet Class
30.2.3 HttpServletRequest Interface Created by servlet container and passed to service method HttpServlet relays the object to doGet or doPost Contains client request and request processing methods
30.2.3 HttpServletRequest Interface
30.2.4 HttpServletResponse Interface Created by servlet container and passed to service method HttpServlet relays the object to doGet or doPost Provides methods to formulate responses
30.2.4 HTTP ServletResponse Interface
30.3 Handling HTTP get Requests Primarily used to retrieve content of a URI Usually HTML or XHTML Can be images or binary data
Upcoming example demonstrates get request handling
WelcomeServlet.java Define WelcomeServlet doGet 1 // Fig. 9.5: WelcomeServlet.java 2 // A simple servlet to process get requests. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet extends HttpServlet { 10 11 // process "get" requests from clients 12 protected void doGet( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 response.setContentType( "text/html" ); 17 PrintWriter out = response.getWriter(); 18 19 // send XHTML page to client 20 21 // start XHTML document 22 out.println( "<?xml version = \"1.0\"?>" ); 23 24 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 25 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 26 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 27 28 out.println( 29 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 30 31 // head section of document 32 out.println( "<head>" ); 33 out.println( "<title>A Simple Servlet Example</title>" ); 34 out.println( "</head>" ); 35 WelcomeServlet.java Define WelcomeServlet doGet Extends HttpServlet to create a Web-based Servlet. Process get request by creating an XHTML document.
WelcomeServlet.java 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 } 45 } WelcomeServlet.java
Main XHTML page which sends a get request to the servlet. 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. 9.6: 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 = "/advjhtp1/welcome1" method = "get"> 14 15 <p><label>Click the button to invoke the servlet 16 <input type = "submit" value = "Get HTML Document" /> 17 </label></p> 18 19 </form> 20 </body> 21 </html> Main XHTML page which sends a get request to the servlet. WelcomeServlet.html
WelcomeServlet.java
30.3.1 Setting up the Apache Tomcat Server Fully functional JSP and Servlet container Includes a Web Server Integrates with popular Web Servers Apache Web Server Microsoft Internet Information Server (IIS) Default Port is 8080
Testing and Debugging Tip 30.1 Fig. 30.7 Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)
30.3.2 Deploying a Web Application Consists of JSPs and servlets Rigid directory structure Often within a Web Application Archive (WAR) Configured via deployment descriptor Web.xml Maps servlet name and location Defines URL pattern
30.3.2 Deploying a Web Application
1 <!-- Advanced Java How to Program JSP/servlet context --> 2 <Context path = "/advjhtp1" 3 docBase = "webapps/advjhtp1" 4 reloadable = "true"> 5 </Context> Fig. 30.9 Context element for servlet and JSP examples in Chapters 30 and 31.
Web.xml Map servlet name and class Map servlet name and URL 1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" 3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> 4 5 <web-app> 6 7 <!-- General description of your Web application --> 8 <display-name> 9 Advanced 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 com.deitel.advjhtp1.servlets.WelcomeServlet 28 </servlet-class> 29 </servlet> 30 31 <!-- Servlet mappings --> 32 <servlet-mapping> 33 <servlet-name>welcome1</servlet-name> Web.xml Map servlet name and class Map servlet name and URL Maps a servlet name to its fully qualified class name.
Fig. 30.10 Deployment descriptor for the advjhtp1 Web application. 34 <url-pattern>/welcome1</url-pattern> 35 </servlet-mapping> 36 37 </web-app> Map servlet to URL pattern. The pattern is relative to the server address and application context root. Fig. 30.10 Deployment descriptor for the advjhtp1 Web application.
30.3.2 Deploying a Web Application
30.4 Handling HTTP get Requests Containing Data Requests and Data Http request follows the format Servlet_url?query_string Query string format Parameter_name=value Name/value pairs separated by &
1 // Fig. 9.12: WelcomeServlet2.java 2 // Processing HTTP get requests containing data. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet2 extends HttpServlet { 10 11 // process "get" request from client 12 protected void doGet( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 String firstName = request.getParameter( "firstname" ); 17 18 response.setContentType( "text/html" ); 19 PrintWriter out = response.getWriter(); 20 21 // send XHTML document to client 22 23 // start XHTML document 24 out.println( "<?xml version = \"1.0\"?>" ); 25 26 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 27 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 28 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 29 30 out.println( 31 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 32 33 // head section of document 34 out.println( "<head>" ); WelcomeServlet2.java Define Servlet WelcomeServlet2 Write XHTML response Obtain the parameter from the request and assign the value to a string.
Include the value in the response. 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 } 49 } WelcomeServlet2.java Include the value in the response.
WelcomeServlet2.html Send get request 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. 9.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 = "/advjhtp1/welcome2" method = "get"> 14 15 <p><label> 16 Type your first name and press the Submit button 17 <br /><input type = "text" name = "firstname" /> 18 <input type = "submit" value = "Submit" /> 19 </p></label> 20 21 </form> 22 </body> 23 </html> WelcomeServlet2.html Send get request
Program Output
30.4 Handling HTTP get Requests Containing Data
30.5 Handling HTTP post Requests Posts data from HTML form Server-side form handler parses data Not cached Ensures client has most updated version Default HttpServlet doPost method disables post
Obtain the firstname parameter from the post request. 1 // Fig. 9.15: WelcomeServlet3.java 2 // Processing post requests containing data. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet3 extends HttpServlet { 10 11 // process "post" request from client 12 protected void doPost( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 String firstName = request.getParameter( "firstname" ); 17 18 response.setContentType( "text/html" ); 19 PrintWriter out = response.getWriter(); 20 21 // send XHTML page to client 22 23 // start XHTML document 24 out.println( "<?xml version = \"1.0\"?>" ); 25 26 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 27 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 28 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 29 30 out.println( 31 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 32 33 // head section of document 34 out.println( "<head>" ); WelcomeServlet3.java Define Servlet WelcomeServlet3 Handle doPost Write XHTML response Obtain the firstname parameter from the post request.
WelcomeServlet3.java 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 } 49 } WelcomeServlet3.java
Submit a post request with a firstname parameter 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. 9.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 = "/advjhtp1/welcome3" method = "post"> 14 15 <p><label> 16 Type your first name and press the Submit button 17 <br /><input type = "text" name = "firstname" /> 18 <input type = "submit" value = "Submit" /> 19 </label></p> 20 21 </form> 22 </body> 23 </html> WelcomeServlet3.html Submit a post request with a firstname parameter
Program Output
30.5 Handling HTTP post Requests
30.6 Redirecting Requests to Other Resources Redirection Allows a Servlet to redirect a request Use sendRedirect method of HttpServletResponse
Obtain the page parameter for redirection location. 1 // Fig. 9.18: RedirectServlet.java 2 // Redirecting a user to a different Web page. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class RedirectServlet extends HttpServlet { 10 11 // process "get" request from client 12 protected void doGet( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 String location = request.getParameter( "page" ); 17 18 if ( location != null ) 19 20 if ( location.equals( "deitel" ) ) 21 response.sendRedirect( "http://www.deitel.com" ); 22 else 23 if ( location.equals( "welcome1" ) ) 24 response.sendRedirect( "welcome1" ); 25 26 // code that executes only if this servlet 27 // does not redirect the user to another page 28 29 response.setContentType( "text/html" ); 30 PrintWriter out = response.getWriter(); 31 32 // start XHTML document 33 out.println( "<?xml version = \"1.0\"?>" ); RedirectServlet.java Define Servlet RedirectServlet Process get request Obtain the page parameter for redirection location. Redirect user to another page or servlet.
RedirectServlet.java Create error page 34 35 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 36 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 37 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 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 } 59 } RedirectServlet.java Create error page
Send get request to RedirectServlet with the page parameter. 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. 9.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 = "/advjhtp1/redirect?page=deitel"> 16 www.deitel.com</a><br /> 17 <a href = "/advjhtp1/redirect?page=welcome1"> 18 Welcome servlet</a> 19 </p> 20 </body> 21 </html> RedirectServlet.html Send get request to RedirectServlet with the page parameter.
Program Output
30.6 Redirecting Requests to Other Resources
30.7 Session Tracking Session Tracking Information techniques Track consumer internet movement Integrate user supplied information Personalization benefits Product targeting Individualized attention Bypass irrelevant content Tracking pitfalls Privacy issues Security of sensitive information
Tracking Technologies 30.7 Session Tracking Tracking Technologies Cookies Section 30.7.1 Session tracking Section 30.7.2 URL rewriting Information embedded in URL parameters Hidden form elements Information contained in hidden form elements Each form retains previous form information
30.7.1 Cookies Cookies Small text data files Often contain unique user identifiers Locates server-side client information Transmitted in HTTP header information Persists for browsing session or maximum age Expires when maximum age reached Lasts for browsing session by default
1 // Fig. 9.21: CookieServlet.java 2 // Using cookies to store data on the client computer. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import java.util.*; 9 10 public class CookieServlet extends HttpServlet { 11 private final Map books = new HashMap(); 12 13 // initialize Map books 14 public void init() 15 { 16 books.put( "C", "0130895725" ); 17 books.put( "C++", "0130895717" ); 18 books.put( "Java", "0130125075" ); 19 books.put( "VB6", "0134569555" ); 20 } 21 22 // receive language selection and send cookie containing 23 // recommended book to the client 24 protected void doPost( HttpServletRequest request, 25 HttpServletResponse response ) 26 throws ServletException, IOException 27 { 28 String language = request.getParameter( "language" ); 29 String isbn = books.get( language ).toString(); 30 Cookie cookie = new Cookie( language, isbn ); 31 32 response.addCookie( cookie ); // must precede getWriter 33 response.setContentType( "text/html" ); 34 PrintWriter out = response.getWriter(); 35 CookieServlet.java Define Servlet CookieServlet Init book ISBN doPost writes cookie Create a new cookie containing the client language and ordered book ISBN number.
CookieServlet.java Write XHTML response 36 // send XHTML page to client 37 38 // start XHTML document 39 out.println( "<?xml version = \"1.0\"?>" ); 40 41 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 42 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 43 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 44 45 out.println( 46 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 47 48 // head section of document 49 out.println( "<head>" ); 50 out.println( "<title>Welcome to Cookies</title>" ); 51 out.println( "</head>" ); 52 53 // body section of document 54 out.println( "<body>" ); 55 out.println( "<p>Welcome to Cookies! You selected " + 56 language + "</p>" ); 57 58 out.println( "<p><a href = " + 59 "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" + 60 "Click here to choose another language</a></p>" ); 61 62 out.println( "<p><a href = \"/advjhtp1/cookies\">" + 63 "Click here to get book recommendations</a></p>" ); 64 out.println( "</body>" ); 65 66 // end XHTML document 67 out.println( "</html>" ); 68 out.close(); // close stream 69 } 70 CookieServlet.java Write XHTML response
CookieServlet.java doGet process get request Obtain user cookies 71 // read cookies from client and create XHTML document 72 // containing recommended books 73 protected void doGet( HttpServletRequest request, 74 HttpServletResponse response ) 75 throws ServletException, IOException 76 { 77 Cookie cookies[] = request.getCookies(); // get cookies 78 79 response.setContentType( "text/html" ); 80 PrintWriter out = response.getWriter(); 81 82 // start XHTML document 83 out.println( "<?xml version = \"1.0\"?>" ); 84 85 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 86 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 87 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 88 89 out.println( 90 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 91 92 // head section of document 93 out.println( "<head>" ); 94 out.println( "<title>Recommendations</title>" ); 95 out.println( "</head>" ); 96 97 // body section of document 98 out.println( "<body>" ); 99 100 // if there are any cookies, recommend a book for each ISBN 101 if ( cookies != null && cookies.length != 0 ) { 102 out.println( "<h1>Recommendations</h1>" ); 103 out.println( "<p>" ); 104 105 // get the name of each cookie Get any cookies from client. CookieServlet.java doGet process get request Obtain user cookies
Cycle through cookies and display book recommendation. 106 for ( int i = 0; i < cookies.length; i++ ) 107 out.println( cookies[ i ].getName() + 108 " How to Program. ISBN#: " + 109 cookies[ i ].getValue() + "<br />" ); 110 111 out.println( "</p>" ); 112 } 113 else { // there were no cookies 114 out.println( "<h1>No Recommendations</h1>" ); 115 out.println( "<p>You did not select a language.</p>" ); 116 } 117 118 out.println( "</body>" ); 119 120 // end XHTML document 121 out.println( "</html>" ); 122 out.close(); // close stream 123 } 124 } Cycle through cookies and display book recommendation. CookieServlet.java
CookieSelectLanguage.html Static XHTML page 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. 9.22: CookieSelectLanguage.html --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Using Cookies</title> 10 </head> 11 12 <body> 13 <form action = "/advjhtp1/cookies" method = "post"> 14 15 <p>Select a programming language:</p> 16 <p> 17 <input type = "radio" name = "language" 18 value = "C" />C <br /> 19 20 <input type = "radio" name = "language" 21 value = "C++" />C++ <br /> 22 23 <!-- this radio button checked by default --> 24 <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java<br /> 26 27 <input type = "radio" name = "language" 28 value = "VB6" />VB 6 29 </p> 30 31 <p><input type = "submit" value = "Submit" /></p> 32 33 </form> 34 </body> 35 </html> CookieSelectLanguage.html Static XHTML page Post user selected language.
Program Output
Program Output
Program Output
30.7.1 Cookies
30.7.1 Cookies
30.7.1 Cookies
30.7.2 Session Tracking with HttpSession HttpSession interface Assigns a unique ID to user Stores name/value pairs, attributes Values are any Java object Expire Browser Session ends Servlet invalidated Servlet container restart
SessionServlet.java Define Servlet SessionServlet 1 // Fig. 9.25: SessionServlet.java 2 // Using HttpSession to maintain client state information. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import java.util.*; 9 10 public class SessionServlet extends HttpServlet { 11 private final Map books = new HashMap(); 12 13 // initialize Map books 14 public void init() 15 { 16 books.put( "C", "0130895725" ); 17 books.put( "C++", "0130895717" ); 18 books.put( "Java", "0130125075" ); 19 books.put( "VB6", "0134569555" ); 20 } 21 22 // receive language selection and create HttpSession object 23 // containing recommended book for the client 24 protected void doPost( HttpServletRequest request, 25 HttpServletResponse response ) 26 throws ServletException, IOException 27 { 28 String language = request.getParameter( "language" ); 29 30 // Get the user's session object. 31 // Create a session (true) if one does not exist. 32 HttpSession session = request.getSession( true ); 33 34 // add a value for user's choice to session SessionServlet.java Define Servlet SessionServlet Obtain client session, if the client does not have a session, create one.
SessionServlet.java Process post request 35 session.setAttribute( language, books.get( language ) ); 36 37 response.setContentType( "text/html" ); 38 PrintWriter out = response.getWriter(); 39 40 // send XHTML page to client 41 42 // start XHTML document 43 out.println( "<?xml version = \"1.0\"?>" ); 44 45 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 46 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 47 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 48 49 out.println( 50 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 51 52 // head section of document 53 out.println( "<head>" ); 54 out.println( "<title>Welcome to Sessions</title>" ); 55 out.println( "</head>" ); 56 57 // body section of document 58 out.println( "<body>" ); 59 out.println( "<p>Welcome to Sessions! You selected " + 60 language + ".</p>" ); 61 62 // display information about the session 63 out.println( "<p>Your unique session ID is: " + 64 session.getId() + "<br />" ); 65 66 out.println( 67 "This " + ( session.isNew() ? "is" : "is not" ) + 68 " a new session<br />" ); 69 SessionServlet.java Process post request
SessionServlet.java process get request 70 out.println( "The session was created at: " + 71 new Date( session.getCreationTime() ) + "<br />" ); 72 73 out.println( "You last accessed the session at: " + 74 new Date( session.getLastAccessedTime() ) + "<br />" ); 75 76 out.println( "The maximum inactive interval is: " + 77 session.getMaxInactiveInterval() + " seconds</p>" ); 78 79 out.println( "<p><a href = " + 80 "\"servlets/SessionSelectLanguage.html\">" + 81 "Click here to choose another language</a></p>" ); 82 83 out.println( "<p><a href = \"sessions\">" + 84 "Click here to get book recommendations</a></p>" ); 85 out.println( "</body>" ); 86 87 // end XHTML document 88 out.println( "</html>" ); 89 out.close(); // close stream 90 } 91 92 // read session attributes and create XHTML document 93 // containing recommended books 94 protected void doGet( HttpServletRequest request, 95 HttpServletResponse response ) 96 throws ServletException, IOException 97 { 98 // Get the user's session object. 99 // Do not create a session (false) if one does not exist. 100 HttpSession session = request.getSession( false ); 101 102 // get names of session object's values 103 Enumeration valueNames; 104 SessionServlet.java process get request Obtain the client session, but do not create one if it does not exist.
Obtain the attributes of the client. Then display any recommendations. 105 if ( session != null ) 106 valueNames = session.getAttributeNames(); 107 else 108 valueNames = null; 109 110 PrintWriter out = response.getWriter(); 111 response.setContentType( "text/html" ); 112 113 // start XHTML document 114 out.println( "<?xml version = \"1.0\"?>" ); 115 116 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 117 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 118 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 119 120 out.println( 121 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 122 123 // head section of document 124 out.println( "<head>" ); 125 out.println( "<title>Recommendations</title>" ); 126 out.println( "</head>" ); 127 128 // body section of document 129 out.println( "<body>" ); 130 131 if ( valueNames != null && 132 valueNames.hasMoreElements() ) { 133 out.println( "<h1>Recommendations</h1>" ); 134 out.println( "<p>" ); 135 136 String name, value; 137 138 // get value for each name in valueNames 139 while ( valueNames.hasMoreElements() ) { Obtain the attributes of the client. Then display any recommendations. SessionServlet.java
SessionServlet.java 140 name = valueNames.nextElement().toString(); 141 value = session.getAttribute( name ).toString(); 142 143 out.println( name + " How to Program. " + 144 "ISBN#: " + value + "<br />" ); 145 } 146 147 out.println( "</p>" ); 148 } 149 else { 150 out.println( "<h1>No Recommendations</h1>" ); 151 out.println( "<p>You did not select a language.</p>" ); 152 } 153 154 out.println( "</body>" ); 155 156 // end XHTML document 157 out.println( "</html>" ); 158 out.close(); // close stream 159 } 160 } SessionServlet.java
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. 9.26: SessionSelectLanguage.html --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Using Sessions</title> 10 </head> 11 12 <body> 13 <form action = "/advjhtp1/sessions" method = "post"> 14 15 <p>Select a programming language:</p> 16 <p> 17 <input type = "radio" name = "language" 18 value = "C" />C <br /> 19 20 <input type = "radio" name = "language" 21 value = "C++" />C++ <br /> 22 23 <!-- this radio button checked by default --> 24 <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java<br /> 26 27 <input type = "radio" name = "language" 28 value = "VB6" />VB 6 29 </p> 30 31 <p><input type = "submit" value = "Submit" /></p> 32 33 </form> 34 </body> 35 </html> SessionSelectLanguage.html XHTML page that allows the client to select a programming language they would like a recommendation for.
Program Output
Program Output
Program Output
30.7.2 Session Tracking with HttpSession
30.8 Multi-tier Applications: Using JDBC from a Servlet Multi-tier Architecture Client Commonly Web browser XHTML HTML Applet Middle Tier Logic component examples: Servlets JSPs Provides interface between client and database
30.8 Multi-tier Applications: Using JDBC from a Servlet Multi-tier Architecture Backend tier Usually a Database Accessed via JDBC from servlets Stores information Client information Product information
30.8 Multi-tier Applications: Using JDBC from a Servlet Java Database Connectivity (JDBC) Provides uniform access to database systems Middle tier will work with any JDBC database Developer not required to write for a specific database Works with SQL-based queries Database interaction handled by JDBC driver Driver usually provided by database vendor
SurveyServlet.java Define servlet SurveyServlet set up database 1 // Fig. 9.27: SurveyServlet.java 2 // A Web-based survey that uses JDBC from a servlet. 3 package com.deitel.advjhtp1.servlets; 4 5 import java.io.*; 6 import java.text.*; 7 import java.sql.*; 8 import javax.servlet.*; 9 import javax.servlet.http.*; 10 11 public class SurveyServlet extends HttpServlet { 12 private Connection connection; 13 private PreparedStatement updateVotes, totalVotes, results; 14 15 // set up database connection and prepare SQL statements 16 public void init( ServletConfig config ) 17 throws ServletException 18 { 19 // attempt database connection and create PreparedStatements 20 try { 21 Class.forName( "COM.cloudscape.core.RmiJdbcDriver" ); 22 connection = DriverManager.getConnection( 23 "jdbc:rmi:jdbc:cloudscape:animalsurvey" ); 24 25 // PreparedStatement to add one to vote total for a 26 // specific animal 27 updateVotes = 28 connection.prepareStatement( 29 "UPDATE surveyresults SET votes = votes + 1 " + 30 "WHERE id = ?" 31 ); 32 33 // PreparedStatement to sum the votes 34 totalVotes = 35 connection.prepareStatement( SurveyServlet.java Define servlet SurveyServlet set up database Specify database driver. Connect to database through that driver. Define SQL query to obtain database information
SurveyServlet.java handle post request 36 "SELECT sum( votes ) FROM surveyresults" 37 ); 38 39 // PreparedStatement to obtain surveyoption table's data 40 results = 41 connection.prepareStatement( 42 "SELECT surveyoption, votes, id " + 43 "FROM surveyresults ORDER BY id" 44 ); 45 } 46 47 // for any exception throw an UnavailableException to 48 // indicate that the servlet is not currently available 49 catch ( Exception exception ) { 50 exception.printStackTrace(); 51 throw new UnavailableException(exception.getMessage()); 52 } 53 54 } // end of init method 55 56 // process survey response 57 protected void doPost( HttpServletRequest request, 58 HttpServletResponse response ) 59 throws ServletException, IOException 60 { 61 // set up response to client 62 response.setContentType( "text/html" ); 63 PrintWriter out = response.getWriter(); 64 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 65 66 // start XHTML document 67 out.println( "<?xml version = \"1.0\"?>" ); 68 69 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 70 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + SurveyServlet.java handle post request
Update database with post parameter. 71 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 72 73 out.println( 74 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); 75 76 // head section of document 77 out.println( "<head>" ); 78 79 // read current survey response 80 int value = 81 Integer.parseInt( request.getParameter( "animal" ) ); 82 83 // attempt to process a vote and display current results 84 try { 85 86 // update total for current survey response 87 updateVotes.setInt( 1, value ); 88 updateVotes.executeUpdate(); 89 90 // get total of all survey responses 91 ResultSet totalRS = totalVotes.executeQuery(); 92 totalRS.next(); 93 int total = totalRS.getInt( 1 ); 94 95 // get results 96 ResultSet resultsRS = results.executeQuery(); 97 out.println( "<title>Thank you!</title>" ); 98 out.println( "</head>" ); 99 100 out.println( "<body>" ); 101 out.println( "<p>Thank you for participating." ); 102 out.println( "<br />Results:</p><pre>" ); 103 104 // process results 105 int votes; SurveyServlet.java Update database with post parameter. Obtain the survey totals and information via SQL requests.
Display results in XHTML response. SurveyServlet.java 106 107 while ( resultsRS.next() ) { 108 out.print( resultsRS.getString( 1 ) ); 109 out.print( ": " ); 110 votes = resultsRS.getInt( 2 ); 111 out.print( twoDigits.format( 112 ( double ) votes / total * 100 ) ); 113 out.print( "% responses: " ); 114 out.println( votes ); 115 } 116 117 resultsRS.close(); 118 119 out.print( "Total responses: " ); 120 out.print( total ); 121 122 // end XHTML document 123 out.println( "</pre></body></html>" ); 124 out.close(); 125 } 126 127 // if database exception occurs, return error page 128 catch ( SQLException sqlException ) { 129 sqlException.printStackTrace(); 130 out.println( "<title>Error</title>" ); 131 out.println( "</head>" ); 132 out.println( "<body><p>Database error occurred. " ); 133 out.println( "Try again later.</p></body></html>" ); 134 out.close(); 135 } 136 137 } // end of doPost method 138 139 // close SQL statements and database when servlet terminates 140 public void destroy() Display results in XHTML response. SurveyServlet.java
SurveyServlet.java Close database 141 { 142 // attempt to close statements and database connection 143 try { 144 updateVo\tes.close(); 145 totalVotes.close(); 146 results.close(); 147 connection.close(); 148 } 149 150 // handle database exceptions by returning error to client 151 catch( SQLException sqlException ) { 152 sqlException.printStackTrace(); 153 } 154 } // end of destroy method 155 } SurveyServlet.java Close database
Static survey XHTML page. 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 <!-- 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 = "/advjhtp1/animalsurvey"> 14 15 <p>What is your favorite pet?</p> 16 17 <p> 18 <input type = "radio" name = "animal" 19 value = "1" />Dog<br /> 20 <input type = "radio" name = "animal" 21 value = "2" />Cat<br /> 22 <input type = "radio" name = "animal" 23 value = "3" />Bird<br /> 24 <input type = "radio" name = "animal" 25 value = "4" />Snake<br /> 26 <input type = "radio" name = "animal" 27 value = "5" checked = "checked" />None 28 </p> 29 30 <p><input type = "submit" value = "Submit" /></p> 31 32 </form> 33 </body> 34 </html> Survey.html Static survey XHTML page.
Program Output
30.8.1 Configuring animalsurvey Database and SurveyServlet
30.9 HttpUtils Class HttpUtils Class Three static utility methods to simplify servlet development
30.9 HttpUtils Class