Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 30 - Servlets: Bonus for Java Developers

Similar presentations


Presentation on theme: "Chapter 30 - Servlets: Bonus for Java Developers"— Presentation transcript:

1 Chapter 30 - Servlets: Bonus for Java Developers
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 Session Tracking Cookies Session Tracking with HttpSession Multi-tier Applications: Using JDBC from a Servlet HttpUtils Class Internet and World Wide Web Resources

2 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.

3 Client-Server Relationship
30.1 Introduction Client-Server Relationship Client sends request, server responds Common implemetation – comunication between Web Server and Web Browser

4 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

5 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

6 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

7 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

8 30.2.1 Interface Servlet and the Servlet Life Cycle

9 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

10 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

11 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

12 HttpServlet Class

13 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

14 30.2.3 HttpServletRequest Interface

15 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

16 30.2.4 HTTP ServletResponse Interface

17 30.3 Handling HTTP get Requests
Primarily used to retrieve content of a URI Usually HTML or XHTML Can be images or binary data

18 Upcoming example demonstrates get request handling

19 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 // process "get" requests from clients protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 18 // send XHTML page to client 20 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 23 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 27 out.println( "<html xmlns = \" ); 30 // head section of document out.println( "<head>" ); out.println( "<title>A Simple Servlet Example</title>" ); 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.

20 WelcomeServlet.java 36 // body section of document
out.println( "<body>" ); out.println( "<h1>Welcome to Servlets!</h1>" ); out.println( "</body>" ); 40 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 45 } WelcomeServlet.java

21 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" " 4 5 <!-- Fig. 9.6: WelcomeServlet.html --> 6 7 <html xmlns = " 8 <head> <title>Handling an HTTP Get Request</title> 10 </head> 11 12 <body> <form action = "/advjhtp1/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> Main XHTML page which sends a get request to the servlet. WelcomeServlet.html

22 WelcomeServlet.java

23 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

24 Testing and Debugging Tip 30.1
Fig Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)

25 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

26 30.3.2 Deploying a Web Application

27 1 <!-- Advanced Java How to Program JSP/servlet context -->
2 <Context path = "/advjhtp1" docBase = "webapps/advjhtp1" reloadable = "true"> 5 </Context> Fig Context element for servlet and JSP examples in Chapters 30 and 31.

28 Web.xml Map servlet name and class Map servlet name and URL
1 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" " 4 5 <web-app> 6 <!-- General description of your Web application --> <display-name> Advanced 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 <servlet-class> com.deitel.advjhtp1.servlets.WelcomeServlet </servlet-class> </servlet> 30 <!-- Servlet mappings --> <servlet-mapping> <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.

29 Fig. 30.10 Deployment descriptor for the advjhtp1 Web application.
<url-pattern>/welcome1</url-pattern> </servlet-mapping> 36 37 </web-app> Map servlet to URL pattern. The pattern is relative to the server address and application context root. Fig Deployment descriptor for the advjhtp1 Web application.

30 30.3.2 Deploying a Web Application

31 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 &

32 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 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); 17 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 20 // send XHTML document to client 22 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 25 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 29 out.println( "<html xmlns = \" ); 32 // head section of document out.println( "<head>" ); WelcomeServlet2.java Define Servlet WelcomeServlet2 Write XHTML response Obtain the parameter from the request and assign the value to a string.

33 Include the value in the response.
out.println( "<title>Processing get requests with data</title>" ); out.println( "</head>" ); 38 // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); 44 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 49 } WelcomeServlet2.java Include the value in the response.

34 WelcomeServlet2.html Send get request
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 9.13: WelcomeServlet2.html --> 6 7 <html xmlns = " 8 <head> <title>Processing get requests with data</title> 10 </head> 11 12 <body> <form action = "/advjhtp1/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> WelcomeServlet2.html Send get request

35 Program Output

36 30.4 Handling HTTP get Requests Containing Data

37 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

38 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 // process "post" request from client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); 17 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 20 // send XHTML page to client 22 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 25 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 29 out.println( "<html xmlns = \" ); 32 // head section of document out.println( "<head>" ); WelcomeServlet3.java Define Servlet WelcomeServlet3 Handle doPost Write XHTML response Obtain the firstname parameter from the post request.

39 WelcomeServlet3.java 35 out.println(
"<title>Processing post requests with data</title>" ); out.println( "</head>" ); 38 // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); 44 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 49 } WelcomeServlet3.java

40 Submit a post request with a firstname parameter
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 9.16: WelcomeServlet3.html --> 6 7 <html xmlns = " 8 <head> <title>Handling an HTTP Post Request with Data</title> 10 </head> 11 12 <body> <form action = "/advjhtp1/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> WelcomeServlet3.html Submit a post request with a firstname parameter

41 Program Output

42 30.5 Handling HTTP post Requests

43 30.6 Redirecting Requests to Other Resources
Redirection Allows a Servlet to redirect a request Use sendRedirect method of HttpServletResponse

44 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 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String location = request.getParameter( "page" ); 17 if ( location != null ) 19 if ( location.equals( "deitel" ) ) response.sendRedirect( " ); else if ( location.equals( "welcome1" ) ) response.sendRedirect( "welcome1" ); 25 // code that executes only if this servlet // does not redirect the user to another page 28 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 31 // start XHTML document 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.

45 RedirectServlet.java Create error page
34 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 38 out.println( "<html xmlns = \" ); 41 // head section of document out.println( "<head>" ); out.println( "<title>Invalid page</title>" ); out.println( "</head>" ); 46 // body section of document out.println( "<body>" ); out.println( "<h1>Invalid page requested</h1>" ); out.println( "<p><a href = " + "\"servlets/RedirectServlet.html\">" ); out.println( "Click here to choose again</a></p>" ); out.println( "</body>" ); 54 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 59 } RedirectServlet.java Create error page

46 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" " 4 5 <!-- Fig. 9.19: RedirectServlet.html --> 6 7 <html xmlns = " 8 <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 = "/advjhtp1/redirect?page=deitel"> /> <a href = "/advjhtp1/redirect?page=welcome1"> Welcome servlet</a> </p> 20 </body> 21 </html> RedirectServlet.html Send get request to RedirectServlet with the page parameter.

47 Program Output

48 30.6 Redirecting Requests to Other Resources

49 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

50 Tracking Technologies
30.7 Session Tracking Tracking Technologies Cookies Section Session tracking Section URL rewriting Information embedded in URL parameters Hidden form elements Information contained in hidden form elements Each form retains previous form information

51 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

52 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 { private final Map books = new HashMap(); 12 // initialize Map books public void init() { books.put( "C", " " ); books.put( "C++", " " ); books.put( "Java", " " ); books.put( "VB6", " " ); } 21 // receive language selection and send cookie containing // recommended book to the client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String language = request.getParameter( "language" ); String isbn = books.get( language ).toString(); Cookie cookie = new Cookie( language, isbn ); 31 response.addCookie( cookie ); // must precede getWriter response.setContentType( "text/html" ); 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.

53 CookieServlet.java Write XHTML response
// send XHTML page to client 37 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 40 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 44 out.println( "<html xmlns = \" ); 47 // head section of document out.println( "<head>" ); out.println( "<title>Welcome to Cookies</title>" ); out.println( "</head>" ); 52 // body section of document out.println( "<body>" ); out.println( "<p>Welcome to Cookies! You selected " + language + "</p>" ); 57 out.println( "<p><a href = " + "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" + "Click here to choose another language</a></p>" ); 61 out.println( "<p><a href = \"/advjhtp1/cookies\">" + "Click here to get book recommendations</a></p>" ); out.println( "</body>" ); 65 // end XHTML document out.println( "</html>" ); out.close(); // close stream } 70 CookieServlet.java Write XHTML response

54 CookieServlet.java doGet process get request Obtain user cookies
// read cookies from client and create XHTML document // containing recommended books protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { Cookie cookies[] = request.getCookies(); // get cookies 78 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 81 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 84 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 88 out.println( "<html xmlns = \" ); 91 // head section of document out.println( "<head>" ); out.println( "<title>Recommendations</title>" ); out.println( "</head>" ); 96 // body section of document out.println( "<body>" ); 99 // if there are any cookies, recommend a book for each ISBN if ( cookies != null && cookies.length != 0 ) { out.println( "<h1>Recommendations</h1>" ); out.println( "<p>" ); 104 // get the name of each cookie Get any cookies from client. CookieServlet.java doGet process get request Obtain user cookies

55 Cycle through cookies and display book recommendation.
for ( int i = 0; i < cookies.length; i++ ) out.println( cookies[ i ].getName() + " How to Program. ISBN#: " + cookies[ i ].getValue() + "<br />" ); 110 out.println( "</p>" ); } else { // there were no cookies out.println( "<h1>No Recommendations</h1>" ); out.println( "<p>You did not select a language.</p>" ); } 117 out.println( "</body>" ); 119 // end XHTML document out.println( "</html>" ); out.close(); // close stream } 124 } Cycle through cookies and display book recommendation. CookieServlet.java

56 CookieSelectLanguage.html Static XHTML page
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 9.22: CookieSelectLanguage.html --> 6 7 <html xmlns = " 8 <head> <title>Using Cookies</title> 10 </head> 11 12 <body> <form action = "/advjhtp1/cookies" method = "post"> 14 <p>Select a programming language:</p> <p> <input type = "radio" name = "language" value = "C" />C <br /> 19 <input type = "radio" name = "language" value = "C++" />C++ <br /> 22 <!-- this radio button checked by default --> <input type = "radio" name = "language" value = "Java" checked = "checked" />Java<br /> 26 <input type = "radio" name = "language" value = "VB6" />VB 6 </p> 30 <p><input type = "submit" value = "Submit" /></p> 32 </form> 34 </body> 35 </html> CookieSelectLanguage.html Static XHTML page Post user selected language.

57 Program Output

58 Program Output

59 Program Output

60 Cookies

61 Cookies

62 Cookies

63 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

64 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 { private final Map books = new HashMap(); 12 // initialize Map books public void init() { books.put( "C", " " ); books.put( "C++", " " ); books.put( "Java", " " ); books.put( "VB6", " " ); } 21 // receive language selection and create HttpSession object // containing recommended book for the client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String language = request.getParameter( "language" ); 29 // Get the user's session object. // Create a session (true) if one does not exist. HttpSession session = request.getSession( true ); 33 // 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.

65 SessionServlet.java Process post request
session.setAttribute( language, books.get( language ) ); 36 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 39 // send XHTML page to client 41 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 44 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 48 out.println( "<html xmlns = \" ); 51 // head section of document out.println( "<head>" ); out.println( "<title>Welcome to Sessions</title>" ); out.println( "</head>" ); 56 // body section of document out.println( "<body>" ); out.println( "<p>Welcome to Sessions! You selected " + language + ".</p>" ); 61 // display information about the session out.println( "<p>Your unique session ID is: " + session.getId() + "<br />" ); 65 out.println( "This " + ( session.isNew() ? "is" : "is not" ) + " a new session<br />" ); 69 SessionServlet.java Process post request

66 SessionServlet.java process get request
out.println( "The session was created at: " + new Date( session.getCreationTime() ) + "<br />" ); 72 out.println( "You last accessed the session at: " + new Date( session.getLastAccessedTime() ) + "<br />" ); 75 out.println( "The maximum inactive interval is: " + session.getMaxInactiveInterval() + " seconds</p>" ); 78 out.println( "<p><a href = " + "\"servlets/SessionSelectLanguage.html\">" + "Click here to choose another language</a></p>" ); 82 out.println( "<p><a href = \"sessions\">" + "Click here to get book recommendations</a></p>" ); out.println( "</body>" ); 86 // end XHTML document out.println( "</html>" ); out.close(); // close stream } 91 // read session attributes and create XHTML document // containing recommended books protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { // Get the user's session object. // Do not create a session (false) if one does not exist. HttpSession session = request.getSession( false ); 101 // get names of session object's values Enumeration valueNames; 104 SessionServlet.java process get request Obtain the client session, but do not create one if it does not exist.

67 Obtain the attributes of the client. Then display any recommendations.
if ( session != null ) valueNames = session.getAttributeNames(); else valueNames = null; 109 PrintWriter out = response.getWriter(); response.setContentType( "text/html" ); 112 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 115 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 119 out.println( "<html xmlns = \" ); 122 // head section of document out.println( "<head>" ); out.println( "<title>Recommendations</title>" ); out.println( "</head>" ); 127 // body section of document out.println( "<body>" ); 130 if ( valueNames != null && valueNames.hasMoreElements() ) { out.println( "<h1>Recommendations</h1>" ); out.println( "<p>" ); 135 String name, value; 137 // get value for each name in valueNames while ( valueNames.hasMoreElements() ) { Obtain the attributes of the client. Then display any recommendations. SessionServlet.java

68 SessionServlet.java 140 name = valueNames.nextElement().toString();
value = session.getAttribute( name ).toString(); 142 out.println( name + " How to Program. " + "ISBN#: " + value + "<br />" ); } 146 out.println( "</p>" ); } else { out.println( "<h1>No Recommendations</h1>" ); out.println( "<p>You did not select a language.</p>" ); } 153 out.println( "</body>" ); 155 // end XHTML document out.println( "</html>" ); out.close(); // close stream } 160 } SessionServlet.java

69 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 9.26: SessionSelectLanguage.html --> 6 7 <html xmlns = " 8 <head> <title>Using Sessions</title> 10 </head> 11 12 <body> <form action = "/advjhtp1/sessions" method = "post"> 14 <p>Select a programming language:</p> <p> <input type = "radio" name = "language" value = "C" />C <br /> 19 <input type = "radio" name = "language" value = "C++" />C++ <br /> 22 <!-- this radio button checked by default --> <input type = "radio" name = "language" value = "Java" checked = "checked" />Java<br /> 26 <input type = "radio" name = "language" value = "VB6" />VB 6 </p> 30 <p><input type = "submit" value = "Submit" /></p> 32 </form> 34 </body> 35 </html> SessionSelectLanguage.html XHTML page that allows the client to select a programming language they would like a recommendation for.

70 Program Output

71 Program Output

72 Program Output

73 30.7.2 Session Tracking with HttpSession

74 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

75 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

76 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

77 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 { private Connection connection; private PreparedStatement updateVotes, totalVotes, results; 14 // set up database connection and prepare SQL statements public void init( ServletConfig config ) throws ServletException { // attempt database connection and create PreparedStatements try { Class.forName( "COM.cloudscape.core.RmiJdbcDriver" ); connection = DriverManager.getConnection( "jdbc:rmi:jdbc:cloudscape:animalsurvey" ); 24 // PreparedStatement to add one to vote total for a // specific animal updateVotes = connection.prepareStatement( "UPDATE surveyresults SET votes = votes + 1 " + "WHERE id = ?" ); 32 // PreparedStatement to sum the votes totalVotes = 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

78 SurveyServlet.java handle post request
"SELECT sum( votes ) FROM surveyresults" ); 38 // PreparedStatement to obtain surveyoption table's data results = connection.prepareStatement( "SELECT surveyoption, votes, id " + "FROM surveyresults ORDER BY id" ); } 46 // 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()); } 53 } // end of init method 55 // 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" ); 65 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 68 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + SurveyServlet.java handle post request

79 Update database with post parameter.
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 72 out.println( "<html xmlns = \" ); 75 // head section of document out.println( "<head>" ); 78 // read current survey response int value = Integer.parseInt( request.getParameter( "animal" ) ); 82 // attempt to process a vote and display current results try { 85 // update total for current survey response updateVotes.setInt( 1, value ); updateVotes.executeUpdate(); 89 // get total of all survey responses ResultSet totalRS = totalVotes.executeQuery(); totalRS.next(); int total = totalRS.getInt( 1 ); 94 // get results ResultSet resultsRS = results.executeQuery(); out.println( "<title>Thank you!</title>" ); out.println( "</head>" ); 99 out.println( "<body>" ); out.println( "<p>Thank you for participating." ); out.println( "<br />Results:</p><pre>" ); 103 // process results int votes; SurveyServlet.java Update database with post parameter. Obtain the survey totals and information via SQL requests.

80 Display results in XHTML response. SurveyServlet.java
106 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 ); } 116 resultsRS.close(); 118 out.print( "Total responses: " ); out.print( total ); 121 // end XHTML document out.println( "</pre></body></html>" ); out.close(); } 126 // 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(); } 136 } // end of doPost method 138 // close SQL statements and database when servlet terminates public void destroy() Display results in XHTML response. SurveyServlet.java

81 SurveyServlet.java Close database
{ // attempt to close statements and database connection try { updateVo\tes.close(); totalVotes.close(); results.close(); connection.close(); } 149 // handle database exceptions by returning error to client catch( SQLException sqlException ) { sqlException.printStackTrace(); } } // end of destroy method 155 } SurveyServlet.java Close database

82 Static survey XHTML page.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Survey.html --> 6 7 <html xmlns = " 8 <head> <title>Survey</title> 10 </head> 11 12 <body> 13 <form method = "post" action = "/advjhtp1/animalsurvey"> 14 <p>What is your favorite pet?</p> 16 <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 Static survey XHTML page.

83 Program Output

84 30.8.1 Configuring animalsurvey Database and SurveyServlet

85 30.9 HttpUtils Class HttpUtils Class
Three static utility methods to simplify servlet development

86 30.9 HttpUtils Class


Download ppt "Chapter 30 - Servlets: Bonus for Java Developers"

Similar presentations


Ads by Google