860 likes | 886 Views
Explore how servlets extend server functionality, interact with databases, and generate dynamic XHTML content. Learn about the servlet life cycle, HTTP requests handling, and session tracking in multi-tier applications.
E N D
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.
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 • Interface Servlet • 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 • 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.3 HttpServletRequest Interface • Interface HttpServletRequest • 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.4 HttpServletResponse Interface • Interface HttpServletResponse • Created by servlet container and passed to service method • HttpServlet relays the object to doGet or doPost • Provides methods to formulate responses
30.3 Handling HTTP get Requests • HTTP get Request • Primarily used to retrieve content of a URI • Usually HTML or XHTML • Can be images or binary data
Extends HttpServlet to create a Web-based Servlet. Process get request by creating an XHTML document. 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.javaDefine WelcomeServletdoGet
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> WelcomeServlet.html
30.3.1 Setting up the Apache Tomcat Server • Tomcat • 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 • 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
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.
Maps a servlet name to its fully qualified class name. 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.xmlMap servlet name and classMap servlet name and URL
Map servlet to URL pattern. The pattern is relative to the server address and application context root. 34 <url-pattern>/welcome1</url-pattern> 35 </servlet-mapping> 36 37 </web-app> Fig. 30.10 Deployment descriptor for the advjhtp1 Web application.
30.4 Handling HTTP get Requests Containing Data • Requests and Data • Http request follows the formatServlet_url?query_string • Query string format • Parameter_name=value • Name/value pairs separated by &
Obtain the parameter from the request and assign the value to a string. 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.javaDefine Servlet WelcomeServlet2Write XHTML response
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
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.htmlSend get request
30.5 Handling HTTP post Requests • HTTP post Request • Posts data from HTML form • Server-side form handler parses data • Not cached • Ensures client has most updated version • Default HttpServletdoPost 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.javaDefine Servlet WelcomeServlet3Handle doPostWrite XHTML response
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
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. Redirect user to another page or servlet. 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.javaDefine Servlet RedirectServletProcess get request
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.javaCreate 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
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
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