Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Unit 09 - Servlet Programming 11.1 11.2 11.2.1 11.2.2 11.2.3 11.2.4 11.3 11.3.1 11.3.2 11.4 11.5 11.6 11.7 11.7.1 11.7.2 11.8 11.9 11.10 11.11 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 Servlet Context Servlet filter Web application listener Java Stream 2 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 • Servlets are modules of Java code that run in a server application to answer client requests. Java Stream 3 Servlet Overview and Architecture • Typical uses for Servlets include: – Processing and/or storing data submitted by an HTML form. – Providing dynamic content, e.g. returning the results of a database query to the client. – Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer • Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic Servlet framework) and javax.servlet.http (extensions of the Servlet framework for Servlets that answer HTTP requests). • Servlet container (servlet engine) – Server that executes a servlet Java Stream 4 Interface Servlet and the Servlet Life Cycle • Interface Servlet – All servlets must implement this interface – All methods of interface Servlet are invoked automatically • 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 Java Stream 5 Interface Servlet and the Servlet Life Cycle (Cont.) Method void init( ServletConfig config ) Description This method is automatically called once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. ServletConfig This method returns a reference to an object that implements getServletConfig( interface ServletConfig. This object provides access to the ) servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). String This method is defined by a servlet programmer to return a getServletInfo() String containing servlet information such as the servlet’s author and version. void service( The servlet container calls this method to respond to a client ServletRequest request to the servlet. request, ServletResponse response ) void destroy() This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here. Methods of interface Servlet (package javax.servlet). Java Stream 6 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 Java Stream 7 HttpServletRequest Interface • Web server – creates an HttpServletRequest object – passes it to the servlet’s service method • HttpServletRequest object contains the request from the client Java Stream 8 HttpServletRequest Interface (Cont.) Method String getParameter( String name ) Enumeration getParameterNames( ) String[] getParameterValues ( String name ) Cookie[] getCookies() Description Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name. Returns the names of all the parameters sent to the servlet as part of a post request. For a parameter with multiple values, this method returns an array of Strings containing the values for a specified servlet parameter. Returns an array of Cookie objects stored on the client by the server. Cookies can be used to uniquely identify clients to the servlet. HttpSession Returns an HttpSession object associated with the client’s getSession( current browsing session. An HttpSession object can be boolean create ) created by this method (true argument) if an HttpSession object does not already exist for the client. HttpSession objects can be used in similar ways to Cookies for uniquely identifying clients. Some methods of interface HttpServletRequest. Java Stream 9 HttpServletResponse Interface HttpServletResponse object contains the request from the client Method void addCookie( Cookie cookie ) Description Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client. ServletOutputStream Obtains a byte-based output stream for sending binary getOutputStream() data to the client. PrintWriter Obtains a character-based output stream for sending text getWriter() data to the client. void setContentType( Specifies the MIME type of the response to the browser. String type ) The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. Some methods of interface HttpServletResponse. Java Stream 10 Handling HTTP GET Requests • GET request – Retrieve the content of a URL • Example: WelcomeServlet – a servlet handles HTTP GET requests Java Stream 11 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // WelcomeServlet.java // A simple servlet to process get requests. package com.alliant.test.servlets; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; WelcomeServlet that responds to a simple Extends HttpServlet HTTP toget handle HTTP get requests request. and HTTP post requests. Override method doGet to provide Lines 5-6 custom get request processing. Import the javax.servlet and javax.servlet.http packages. public class WelcomeServlet extends HttpServlet { // process "get" requests from clients protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); Line 9 Uses the response object’s Uses the responsemethod object’stogetWriter setContentType specify method to obtain a reference Lines 12-44 the content type of the data totobethe PrintWriter object that enables sent as the response to the client.the servlet to send content the client. Line to16 Create the XHTML document by writing strings with the out Line 17 object’s println method. Lines 22-42 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>A Simple Servlet Example</title>" ); out.println( "</head>" ); Java Stream 12 36 37 38 39 40 41 42 43 44 45 // body section of document out.println( "<body>" ); out.println( "<h1>Welcome to Servlets!</h1>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } } Outline WelcomeServlet that responds Closes to the output stream, a simple flushesHTTP the output getbuffer and sends the information request. to the client. Line 43 Java Stream 13 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- WelcomeServlet.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Handling an HTTP Get Request</title> </head> <body> <form action = "/test/welcome1" method = "get"> Outline HTML document in which the form’s action invokes WelcomeServlet through the alias welcome1 specified in web.xml. <p><label>Click the button to invoke the servlet <input type = "submit" value = "Get HTML Document" /> </label></p> </form> </body> </html> Java Stream 14 Setting Up the Apache Tomcat Server • Download Tomcat (version 5.0.27) – http://jakarta.apache.org/builds/jakarta-tomcat/ • Define environment variables – JAVA_HOME – CATALINA_HOME • Start the Tomcat server – CATALINA_HOME\bin\startup.bat • Launch the Tomcat server – http://localhost:8080/ • Shutdown the Tomcat server – CATALINA_HOME\bin\shutdown.bat Java Stream 15 Setting Up the Apache Tomcat Server (Cont.). Tomcat documentation home page. (Courtesy of The Apache Software Foundation.) Java Stream 16 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) OR Web application folder – Deployment descriptor • web.xml Java Stream 17 Deploying a Web Application (Cont.) Directory context root Description This is the root directory for the Web application. The name of this directory is chosen by the Web application developer. All the JSPs, HTML documents, servlets and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the Web application creator. To provide structure in a Web application, subdirectories can be placed in the context root. For example, if your application uses many images, you might place an images subdirectory in this directory. WEB-INF This directory contains the Web application deployment descriptor (web.xml). WEB-INF/classes This directory contains the servlet class files and other supporting class files used in a Web application. If the classes are part of a package, the complete package directory structure would begin here. WEB-INF/lib This directory contains Java archive (JAR) files. The JAR files can contain servlet class files and other supporting class files used in a Web application. Web application standard directories. Java Stream 18 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> Outline Element web-app defines the configuration Deployment of each servlet in the Web application and descriptor <!-- General description ofthe your Web application --> each servlet. servlet mapping for (web.xml) for <display-name> Element display-name specifies a the advjhtp1 Sample name that can be displayed to the Servlet Examples Web </display-name> administrator of the server on which application. the Web application is installed. <description> Element description specifies This is the Web application in which we Lines 5-37 a description of the Web application demonstrate our JSP and Servlet examples. </description> that might be displayed the Lines to 8-11 administrator of the server. <!-- Servlet definitions --> Element servlet describes a servlet. <servlet> 13-16 Element servlet-nameLines is <web-app> <servlet-name>welcome1</servlet-name> <description> A simple servlet that handles an HTTP get request. </description> <servlet-class> com.alliant.test.servlets.WelcomeServlet </servlet-class> </servlet> the name for the servlet. Lines 19-29 Element description specifies a description for Line 20servlet. this particular Element servlet-class specifiesLines compiled22-24 servlet’s fully qualified class name. Lines 26-28 Java Stream 19 31 32 33 34 35 36 37 <!-- Servlet mappings --> <servlet-mapping> <servlet-name>welcome1</servlet-name> <url-pattern>/welcome1</url-pattern> </servlet-mapping> </web-app> Outline Element servlet-mapping specifies servlet-name and Deployment url-pattern elements. descriptor (web.xml) for the advjhtp1 Web application. Lines 32-35 Java Stream 20 Deploying a Web Application (Cont.) • Invoke WelcomeServlet example – /test/welcome1 • /test specifies the context root • /welcome1 specifies the URL pattern • URL pattern formats – Exact match • /test/welcome1 – Path mappings • /test/example/* – Extension mappings • *.jsp – Default servlet • /test/example/ Java Stream 21 Deploying a Web Application (Cont.) WelcomeServlet Web application directory and file structure test servlets WelcomeServlet.html WEB-INF web.xml classes com alliant test servlets WelcomeServlet.class Web application directory and file structure for WelcomeServlet. Java Stream 22 Handling HTTP GET Requests Containing Data • Servlet WelcomeServlet2 – Responds to a get request that contains data Java Stream 23 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // WelcomeServlet2.java // Processing HTTP get requests containing data. package com.alliant.test.servlets; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet2 extends HttpServlet { // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML document to client Outline WelcomeServlet2 responds to a get request that contains data. Line 16 The request object’s getParameter method receives the parameter name and returns the corresponding String value. // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); Java Stream 24 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 // head section of document out.println( "<head>" ); out.println( "<title>Processing get requests with data</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); Outline WelcomeServlet2 responds to a get request Uses the resultcontains of line that 16 as part of the data. response to the client. Line 41 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } } Java Stream 25 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- WelcomeServlet2.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Processing get requests with data</title> </head> <body> <form action = "/test/welcome2" method = "get"> <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </p></label> Outline HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Get the first name from theLine user. 17 </form> </body> </html> Java Stream 26 Outline HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Program output Java Stream 27 Handling HTTP get Requests Containing Data (Cont.) Descriptor element servlet element Value servlet-name welcome2 description Handling HTTP get requests with data. servlet-class com.deitel.test.servlets.WelcomeServlet2 servlet-mapping element servlet-name welcome2 url-pattern /welcome2 Deployment descriptor information for servlet WelcomeServlet2. Java Stream 28 Handling HTTP post Requests • HTTP post request – 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 Java Stream 29 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // WelcomeServlet3.java // Processing post requests containing data. package com.deitel.advjhtp1.servlets; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet3 extends HttpServlet { // process "post" request from client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); Outline WelcomeServlet3 responds to a post request that contains data. Linesto12-48 Define a doPost method responds to post requests. response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); Java Stream 30 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 // head section of document out.println( "<head>" ); out.println( "<title>Processing post requests with data</title>" ); out.println( "</head>" ); Outline WelcomeServlet3 .java // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } } Java Stream 31 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 9.15: WelcomeServlet3.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Handling an HTTP Post Request with Data</title> </head> <body> <form action = "/test/welcome3" method = "post"> <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </label></p> Outline HTML document in which the form’s action invokes WelcomeServlet3 through the Provide alias a form inwelcome3 which the user canspecified input a name in inthe text input element firstname, web.xml. then click the Submit button to invoke WelcomeServlet3. Lines 13-21 </form> </body> </html> Java Stream 32 Outline HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Program output Java Stream 33 Handling HTTP post Requests (Cont.) Descriptor element servlet element Value servlet-name welcome3 description Handling HTTP post requests with data. servlet-class com.deitel.test.servlets.WelcomeServlet3 servlet-mapping element servlet-name welcome3 url-pattern /welcome3 Deployment descriptor information for servlet WelcomeServlet3. Java Stream 34 Redirecting Requests to Other Resources • Servlet RedirectServlet – Redirects the request to a different resource Java Stream 35 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Outline // RedirectServlet.java // Redirecting a user to a different Web page. package com.deitel.advjhtp1.servlets; Redirecting requests to other resources. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class RedirectServlet extends HttpServlet { Line 16 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String location = request.getParameter( "page" ); Lines 20-24 Obtains the page parameter from the Line request.21 if ( location != null ) if ( location.equals( “alliant" ) ) response.sendRedirect( "http://www.alliant-corp.com" else if ( location.equals( "welcome1" ) ) response.sendRedirect( "welcome1" ); // code that executes only if this servlet // does not redirect the user to another page response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 24is either Determine if Line the value the request to “deitel”Redirects or “welcome1” www.deitel.com. Lines 29-56 ); Redirects the request to the servlet WelcomeServlet. Output a Web page indicating that an invalid request was made if method sendRedirect is not called. Java Stream 36 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); Outline Redirecting requests to other resources. // head section of document out.println( "<head>" ); out.println( "<title>Invalid page</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<h1>Invalid page requested</h1>" ); out.println( "<p><a href = " + "\"servlets/RedirectServlet.html\">" ); out.println( "Click here to choose again</a></p>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } } Java Stream 37 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- RedirectServlet.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Redirecting a Request to Another Site</title> </head> Outline RedirectServlet .html document to demonstrate redirecting requests to other resources. <body> Provide hyperlinks that Lines 15-16 <p>Click a link to be redirected to the appropriate page</p> allow the user to invoke the <p> servlet RedirectServlet. <a href = "/test/redirect?page=alliant"> Lines 17-18 www.alliant-corp.com</a><br /> <a href = "/test/redirect?page=welcome1"> Welcome servlet</a> </p> </body> </html> Java Stream 38 Redirecting Requests to other Resources (Cont.) Descriptor element Value servlet element servlet-name description redirect Redirecting to static Web pages and other servlets. com.deitel.advjhtp1.servlets.RedirectServlet servlet-class servlet-mapping element redirect servlet-name /redirect url-pattern Deployment descriptor information for servlet RedirectServlet. Java Stream 39 Session Tracking • Personalization • Privacy invasion • HTTP – stateless protocol – Does not support persistent information • Track clients individually – Cookies – Session tracking – hidden type input – URL rewriting Java Stream 40 Cookies • • • • • Stored on the user’s computer for retrieval later Text-based data sent by servlets Maximum age of a cookie Deleted automatically when they expire Servlet CookieServlet – Handles both get and post requests Java Stream 41 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // CookieServlet.java // Using cookies to store data on the client computer. package com.alliant.test.servlets; import import import import Storing user data on the client computer with cookies. javax.servlet.*; javax.servlet.http.*; java.io.*; java.util.*; public class CookieServlet extends HttpServlet { private final Map books = new HashMap(); // initialize Map books public void init() { books.put( "C", "0130895725" ); books.put( "C++", "0130895717" ); books.put( "Java", "0130125075" ); books.put( "VB6", "0134569555" ); } Outline Lines 14-20 Method init populates books with Line 28 four key/value pair of books. Line 29 Line 30 // 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 ); response.addCookie( cookie ); // must precede response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); Line 32 Uses method GetsgetParameter the ISBN number to for the Creates a new Cookie object, selected from books. obtainlanguage the user’s using the language and isbn Adds the cookie to thelanguage responseselection. getWriter values as the cookie name and with method addCookie of cookie value, respectively. interface HttpServletResponse. Java Stream 42 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 // send XHTML page to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); Outline Storing user data on the client computer with cookies. out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Welcome to Cookies</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<p>Welcome to Cookies! You selected " + language + "</p>" ); out.println( "<p><a href = " + "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" + "Click here to choose another language</a></p>" ); out.println( "<p><a href = \"/advjhtp1/cookies\">" + "Click here to get book recommendations</a></p>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream } Java Stream 43 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 // 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 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); Outline Storing user datafrom onthe the Retrieves the cookies client computer client using HttpServletRequest with cookies. method getCookies, which returns an array of Cookie objects. Line 77 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Recommendations</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); // if there are if ( cookies != out.println( out.println( any cookies, recommend a book for each ISBN null && cookies.length != 0 ) { "<h1>Recommendations</h1>" ); "<p>" ); Java Stream 44 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 // get the name of each cookie for ( int i = 0; i < cookies.length; i++ ) out.println( cookies[ i ].getName() + " How to Program. ISBN#: " + cookies[ i ].getValue() + "<br />" ); out.println( "</p>" ); } else { // there were no cookies out.println( "<h1>No Recommendations</h1>" ); out.println( "<p>You did not select a language.</p>" ); } Outline Storing user data on the client computer with cookies. out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream } } Java Stream 45 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- CookieSelectLanguage.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using Cookies</title> </head> <body> <form action = "/advjhtp1/cookies" method = "post"> <p>Select a programming language:</p> <p> <input type = "radio" name = "language" value = "C" />C <br /> Outline CookieSelectLan guage.html document for selecting a programming language and posting the data to the CookieServlet. <input type = "radio" name = "language" value = "C++" />C++ <br /> <!-- this radio button checked by default --> <input type = "radio" name = "language" value = "Java" checked = "checked" />Java<br /> <input type = "radio" name = "language" value = "VB6" />VB 6 </p> <p><input type = "submit" value = "Submit" /></p> </form> </body> </html> Java Stream 46 Outline CookieSelectLan guage.html document for selecting a programming language and posting the data to the CookieServlet. Program output Java Stream 47 Outline CookieSelectLan guage.html document for selecting a programming language and posting the data to the CookieServlet. Program output Java Stream 48 Cookies (Cont.) Descriptor element servlet element Value servlet-name cookies description Using cookies to maintain state information. servlet-class com.deitel.advjhtp1.servlets.CookieServlet servlet-mapping element servlet-name cookies url-pattern /cookies Deployment descriptor information for servlet CookieServlet. Java Stream 49 Cookies (Cont.) M e tho d getComment() getDomain() getMaxAge() getName() getPath() getSecure() getValue() getVersion() De sc rip tio n Returns a String describing the purpose of the cookie (null if no comment has been set with setComment). Returns a String containing the cookie’s domain. This determines which servers can receive the cookie. By default, cookies are sent to the server that originally sent the cookie to the client. Returns an int representing the maximum age of the cookie in seconds. Returns a String containing the name of the cookie as set by the constructor. Returns a String containing the URL prefix for the cookie. Cookies can be “targeted” to specific URLs that include directories on the Web server. By default, a cookie is returned to services operating in the same directory as the service that sent the cookie or a subdirectory of that directory. Returns a boolean value indicating if the cookie should be transmitted using a secure protocol (true). Returns a String containing the value of the cookie as set with setValue or the constructor. Returns an int containing the version of the cookie protocol used to create the cookie. A value of 0 (the default) indicates the original cookie protocol as defined by Netscape. A value of 1 indicates the current version, which is based on Request for Comments (RFC) 2109. (Part 1 of 2) Important methods of class Cookie. Java Stream 50 Cookies (Cont.) setComment( String ) The comment describing the purpose of the cookie that is presented by the browser to the user. (Some browsers allow the user to accept cookies on a per-cookie basis.) setDomain( String ) This determines which servers can receive the cookie. By default, cookies are sent to the server that originally sent the cookie to the client. The domain is specified in the form ".alliant.com", indicating that all servers ending with .alliant.com can receive this cookie. setMaxAge( int ) Sets the maximum age of the cookie in seconds. setPath( String ) Sets the “target” URL prefix indicating the directories on the server that lead to the services that can receive this cookie. setSecure( boolean A true value indicates that the cookie should only be sent ) using a secure protocol. setValue( String ) Sets the value of a cookie. setVersion( int ) Sets the cookie protocol for this cookie. (Part 2 of 2) Important methods of class Cookie. Java Stream 51 Session How Do We Need HTTP State? • Web applications need to track the users across a series of requests: – Online shopping (e.g. Order books) – Financial portfolio manager – Movie listings • HTTP does not support directly • Need a mechanism to maintain state about a series of requests from the same user ( or originating from the same browser) over some period of time Java Stream 52 Session Tracking Overview • The servlet API has a built-in support for session tracking • Session objects live on the server – Each user has associated an HttpSession object—one user/session – HttpSession object operates like a hashtable Java Stream 53 Session Tracking with HttpSession • To get a user's existing or new session object: – HttpSession session = request.getSession(true); – "true" means the server should create a new session object if necessary • To store or retrieve an object in the session: – Stores values: setAttribute("cartItem", cart); – Retrieves values: getAttribute("cartItem"); Java Stream 54 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // SessionServlet.java // Using HttpSession to maintain client state information. package com.deitel.test.servlets; import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.util.*; public class SessionServlet extends HttpServlet { private final Map books = new HashMap(); // initialize Map books public void init() { books.put( "C", "0130895725" ); books.put( "C++", "0130895717" ); books.put( "Java", "0130125075" ); books.put( "VB6", "0134569555" ); } // 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" ); // Get the user's session object. // Create a session (true) if one does not exist. HttpSession session = request.getSession( true ); // add a value for user's choice to session session.setAttribute( language, books.get( language ) ); Outline Maintaining state information with HttpSession objects. Line 28 Line 32 Line 35 Gets the user’s Uses setAttribute to selection. put the language language the corresponding Usesand method getSession of recommended ISBN number interface book’s HttpServletRequest into the HttpSession object. to obtain the HttpSession object for the client. Java Stream 55 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Welcome to Sessions</title>" ); out.println( "</head>" ); Outline Maintaining state information with HttpSession objects. Line 64 Line 67 // body section of document out.println( "<body>" ); out.println( "<p>Welcome to Sessions! You selected " + language + ".</p>" ); // display information about the session out.println( "<p>Your unique session ID is: " + session.getId() + "<br />" ); out.println( "This " + ( session.isNew() ? "is" : "is not" ) + " a new session<br />" ); Uses HttpSession method getID to obtain the session’s unique ID number. Determines whether the session is new or already exists with method isNew. Java Stream 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 out.println( "The session was created at: " + new Date( session.getCreationTime() ) + "<br />" ); out.println( "You last accessed the session at: " + new Date( session.getLastAccessedTime() ) + "<br />" ); out.println( "The maximum inactive interval is: " + session.getMaxInactiveInterval() + " seconds</p>" ); out.println( "<p><a href = " + "\"servlets/SessionSelectLanguage.html\">" + "Click here to choose another language</a></p>" ); out.println( "<p><a href = \"sessions\">" + "Click here to get book recommendations</a></p>" ); out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream } // 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 ); // get names of session object's values Enumeration valueNames; Obtains the time at which the 56 Outline time atwith sessionObtains was lastthe accessed the session was methodwhich getLastAccessedTime. created with method Fig. 9.24 getCreationTime. Maintaining state information Uses method getMaxInactiveInterval to with obtain the maximumHttpSession amount of time that an HttpSession object can be inactive objects. before the servlet container discards it. Line 71 Line 74 Line 77 Line 100 Obtains the HttpSession object for the client with method getSession. Java Stream 57 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 if ( session != null ) valueNames = session.getAttributeNames(); else valueNames = null; PrintWriter out = response.getWriter(); response.setContentType( "text/html" ); // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); Outline Uses HttpSession method getAttributeNames to retrieve an Enumeration of Maintaining the attribute names. state information with HttpSession objects. Line 106 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); out.println( "<title>Recommendations</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); if ( valueNames != null && valueNames.hasMoreElements() ) { out.println( "<h1>Recommendations</h1>" ); out.println( "<p>" ); String name, value; Java Stream 58 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 // get value for each name in valueNames while ( valueNames.hasMoreElements() ) { name = valueNames.nextElement().toString(); value = session.getAttribute( name ).toString(); out.println( name + " How to Program. " + "ISBN#: " + value + "<br />" ); } out.println( "</p>" ); } else { out.println( "<h1>No Recommendations</h1>" ); out.println( "<p>You did not select a language.</p>" ); } Outline Invokes method Maintaining getAttribute of state to retrieve HttpSession the information ISBN of a book from the with HttpSession object. HttpSession objects. Line 141 out.println( "</body>" ); // end XHTML document out.println( "</html>" ); out.close(); // close stream } } Java Stream 59 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- SessionSelectLanguage.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using Sessions</title> </head> <body> <form action = "/test/sessions" method = "post"> <p>Select a programming language:</p> <p> <input type = "radio" name = "language" value = "C" />C <br /> Outline SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. <input type = "radio" name = "language" value = "C++" />C++ <br /> <!-- this radio button checked by default --> <input type = "radio" name = "language" value = "Java" checked = "checked" />Java<br /> <input type = "radio" name = "language" value = "VB6" />VB 6 </p> <p><input type = "submit" value = "Submit" /></p> </form> </body> </html> Java Stream 60 Outline SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output Java Stream 61 Outline SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output Java Stream 62 Outline SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output Java Stream 63 Outline SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output Java Stream 64 Session Tracking with HttpSession (Cont.) Descriptor element servlet element Value servlet-name sessions description Using sessions to maintain state information. servlet-class com.alliant.test.servlets.SessionServlet servlet-mapping element servlet-name sessions url-pattern /sessions Deployment descriptor information for servlet WelcomeServlet2. Java Stream 65 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 – MySQL database Java Stream 66 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline // SurveyServlet.java // A Web-based survey that uses JDBC from a servlet. package com.alliant.test.servlets; import import import import import Multi-tier Webbased survey using XHTML, servlets and JDBC. java.io.*; java.text.*; java.sql.*; javax.servlet.*; javax.servlet.http.*; public class SurveyServlet extends HttpServlet { private Connection connection; private PreparedStatement updateVotes, totalVotes, results; Lines 16-54 // 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.mysql.jdbc.Driver" ); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test" ); Line 21 Servlets are initialized by overriding method init. Lines 22-23 Loads the 27-31 Lines Attemptdatabase to open adriver. connection to the animalsurvey database. // PreparedStatement to add one to vote total for a // specific animal updateVotes = connection.prepareStatement( "UPDATE surveyresults SET votes = votes + 1 " + "WHERE id = ?" ); Create PreparedStatement updateVotes object. Java Stream 67 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // PreparedStatement to sum the votes totalVotes = connection.prepareStatement( "SELECT sum( votes ) FROM surveyresults" ); // PreparedStatement to obtain surveyoption table's data results = connection.prepareStatement( "SELECT surveyoption, votes, id " + "FROM surveyresults ORDER BY id" ); } Outline Multi-tier WebCreate PreparedStatement survey totalVotesbased and results objects. using XHTML, servlets and JDBC. Lines 34-44 // 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()); } } // end of init method // 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" ); Java Stream 68 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); // head section of document out.println( "<head>" ); Outline Multi-tier Webbased survey using XHTML, servlets and JDBC. Lines 80-81 // read current survey response int value = Integer.parseInt( request.getParameter( "animal" ) ); Obtain the survey response Lines 87-88 // attempt to process a vote and display current results try { Lines 91-93 // update total for current surevy response updateVotes.setInt( 1, value ); updateVotes.executeUpdate(); // get total of all survey responses ResultSet totalRS = totalVotes.executeQuery(); totalRS.next(); int total = totalRS.getInt( 1 ); // get results ResultSet resultsRS = results.executeQuery(); out.println( "<title>Thank you!</title>" ); out.println( "</head>" ); Lines 96-123 Set the first parameter of PreparedStatement updateVotes to the survey response and update the database. Execute PreparedStatement totalVotes to retrieve the total number of votes received. Execute PreparedStatement results and process the ResultSet to create the survey summary for the client. Java Stream 69 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 out.println( "<body>" ); out.println( "<p>Thank you for participating." ); out.println( "<br />Results:</p><pre>" ); // process results int votes; while ( resultsRS.next() ) { out.print( resultsRS.getString( 1 ) ); out.print( ": " ); votes = resultsRS.getInt( 2 ); out.print( twoDigits.format( ( double ) votes / total * 100 ) ); out.print( "% responses: " ); out.println( votes ); } Outline Multi-tier Webbased survey using XHTML, servlets and JDBC. resultsRS.close(); out.print( "Total responses: " ); out.print( total ); // end XHTML document out.println( "</pre></body></html>" ); out.close(); } // 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(); Java Stream 70 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 } } // end of doPost method Methodwhen destroy closesterminates // close SQL statements and database servlet each PreparedStatement public void destroy() and database connection. { // attempt to close statements and database connection try { updateVotes.close(); totalVotes.close(); results.close(); connection.close(); } } Outline Multi-tier Webbased survey using XHTML, servlets and JDBC. Lines 140-154 // handle database exceptions by returning error to client catch( SQLException sqlException ) { sqlException.printStackTrace(); } // end of destroy method } Java Stream 71 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Survey.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Survey</title> </head> <body> <form method = "post" action = "/test/animalsurvey"> Outline Survey.html document that allows users to submit survey responses to SurveyServlet. <p>What is your favorite pet?</p> <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> <p><input type = "submit" value = "Submit" /></p> </form> </body> </html> Java Stream 72 Outline Survey.html document that allows users to submit survey responses to SurveyServlet. Java Stream 73 Multi-Tier Applications: Using JDBC from a Servlet (Cont.) Descriptor element servlet element Value servlet-name animalsurvey description Connecting to a database from a servlet. servlet-class com.alliant.test.servlets.SurveyServlet servlet-mapping element servlet-name animalsurvey url-pattern /animalsurvey Deployment descriptor information for servlet SurveyServlet. Java Stream 74 Servlet Context • Defined by an object of ServletContext type. • Defines a servlet’s view of the web application within which the servlet is running. • Allows a servlet to access resources available to it. • Using such an object, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. Java Stream 75 Servlet Context - Sample • We can change the init() method of the SurveyServlet as below: • Then we need to amend the web.xml file to specify the initial context parameters: Java Stream 76 Sending Multimedia Content • People want to return different MIME types • The most common use of a different MIME type is for returning an image graphic generated by a servlet • The example next slide is an example of a servlet that generates and returns a GIF image. The graphic says “Hello World!” Java Stream 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 35 36 // HelloWorldGraphics .java // A simple servlet to generate an on the fly image. package com.alliant.test.servlets; import import import import public javax.servlet.*; javax.servlet.http.*; java.io.*; Acme.JPM.Encoders.GifEncoder; class HelloWorldGraphics extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getOutputStream(); // binary output! 77 Outline HelloWorldGraphics that responds to with a gif graphic Frame frame = null; Graphics g = null; try { // Create an unshown frame frame = new Frame(); frame.addNotify(); // Get a graphics region, using the Frame Image image = frame.createImage(400, 60); g = image.getGraphics(); // Draw "Hello World!" to the off-screen graphics context g.setFont(new Font("Serif", Font.ITALIC, 48)); g.drawString("Hello World!", 10, 50); // Encode the off-screen image into a GIF and send it to the client res.setContentType("image/gif"); GifEncoder encoder = new GifEncoder(image, out); encoder.encode(); } finally { // Clean up resources if (g != null) g.dispose(); if (frame != null) frame.removeNotify(); } } } Java Stream 78 Servlet Filter • New component framework • Dynamically intercepting and modifying requests and responses • Apply filters to web components or pages • Allows range of activities: – Marking access, blocking access – Content transformations • Works on Tomcat4.0 and above • Examples of servlet filters can be found on: • http://java.sun.com/developer/EJTechTips/2002/tt0813.html • http://java.sun.com/developer/EJTechTips/2002/tt0919.html#1 Java Stream 79 What is a Filter? • A reusable piece of code • Transform the content of HTTP requests, response, and header information • Do not generally create response or responding to requests • Attached to one or more servlets • Modify or adapt the request/response for a resource • Act on dynamic or static content – web resources Java Stream 80 Importance and Benefits • Provide the ability to encapsulate recurring tasks in reusable units – Developers have ways to modularize the code – Code is more manageable, documentable, reusable and easy to debug • Separate high-level access decisions from presentation code – Separate business logic from presentation • Apply wholesale changes to many different resources Java Stream 81 Examples of Filters • Authentication – Blocking requests based on user identity • Logging and auditing – Tracking user of a web application • Image conversion – Scaling maps, and so on • Localization – Targeting the request and response to a particular locale • XSLT transformations of XML content – Targeting web application response s to more than one type of client Java Stream 82 Examples of Filters (Cont) • Data compression – Making downloads smaller • • • • • Encryption Filters that trigger resource access events Mime-type chain filters Caching … Java Stream 83 Type of Filters • pre-processing servlet filter • The client sends a request to the server. The servlet filter intercepts the request. • The servlet filter pre-processes the request. • The servlet filter calls chain.doFilter to invoke either the next filter in the chain, or the target Web component. • The Web component returns a response to the client. Java Stream 84 Type of Filters • post-processing servlet filter • • The client sends a request to the server. The servlet filter intercepts the request. The servlet filter passes the request to the filter chain by calling chain.doFilter. After all filters have been invoked, the Web component returns its content. The servlet filter post-processes the Web component's response. • The filter returns the response to the client. • • Java Stream 85 Multiple Filters Java Stream 86 How Servlet Filter Work? Java Stream 87 Basic Steps to Create Filters • Create a class that implements the Filter interface – Implement three methods doFilter(), init(), and destroy() • Put filtering behavior in doFilter() method • Call doFilter() method of FilterChain object – When doFilter() is invoked from FilterChain object, the next associated filter is invoked – If no other filter is associated, servlets themselves invoked • Register the filter with appropriate servlets and JSP pages – Use filter and filter-mapping elements in the deployment descriptor(web.xml) – Apply filters to resources by specifying the URL to which filters apply Java Stream 88 Filter - Code Samples • Blocking filter: – Filter that refuses access to anyone connecting directly from or following a link from a banned site Java Stream 89 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.net.*; public class BannedAccessFilter implements Filter { private HashSet bannedSiteTable; /** Deny access if the request comes from a banned site * or is referred here by a banned site. */ Outline BannedAccessFilter.j ava public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; String requestingHost = req.getRemoteHost(); String referringHost = getReferringHost(req.getHeader("Referer")); String bannedSite = null; boolean isBanned = false; if (bannedSiteTable.contains(requestingHost)) { bannedSite = requestingHost; isBanned = true; } else if (bannedSiteTable.contains(referringHost)) { bannedSite = referringHost; isBanned = true; } Java Stream 90 if (isBanned) { showWarning(response, bannedSite); } else { chain.doFilter(request,response); } Outline BannedAccessFilter.j ava } /** Create a table of banned sites based on initialization * parameters . Remember that version 2.3 of the servlet * API mandates the use of the Java 2 Platform. Thus, * it is safe to use HashSet (which determines whether * a given key exists) rather than the clumsier * Hashtable (which has a value for each key). */ public void init(FilterConfig config) throws ServletException { bannedSiteTable = new HashSet(); String bannedSites = config.getInitParameter("bannedSites"); // Default token set: white space. StringTokenizer tok = new StringTokenizer(bannedSites); while(tok.hasMoreTokens()) { String bannedSite = tok.nextToken(); bannedSiteTable.add(bannedSite); System.out.println("Banned " + bannedSite); } } Java Stream 91 public void destroy() {} private String getReferringHost(String refererringURLString) { try { URL referringURL = new URL(refererringURLString); return(referringURL.getHost()); } catch(MalformedURLException mue) { // Malformed or null return(null); } } Outline BannedAccessFilter.j ava // Replacement response that is returned to users // who are from or referred here by a banned site. private void showWarning(ServletResponse response, String bannedSite) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; Java Stream 92 out.println (docType + "<HTML>\n" + "<HEAD><TITLE>Access Prohibited</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"WHITE\">\n" + "<H1>Access Prohibited</H1>\n" + "Sorry, access from or via " + bannedSite + "\n" + "is not allowed.\n" + "</BODY></HTML>"); } Outline BannedAccessFilter.j ava } Java Stream 93 Blocking Access Filter Configuration: Web.xml Java Stream 94 Servlet Lifecycle Events • From Java Servlet 2.3 • New events framework • More global control than any one servlet or JSP can provide • Support event notifications for state changes in ServletContext and HttpSession objects • Scope – ServletContext: manage state held at a VM level for the application – HttpSession: manage state or resources associated with a series of requests from the same user/session – In distributed containers, one listener instance /deployment descriptor declaration / java VM Java Stream 95 ServletContext and HttpSession • Interesting things on the servlet contexts: – Manage – Startup/shutdown – Attribute changes • Interesting events on HTTP sessions: – Creation and invalidation – Changes in attributes – Migration across distributed containers • Attribute changes to both objects may occur concurrently – No synchronization support in container – Listener classes need to support data integrity Java Stream 96 Java Servlet 2.3 API— Listening Interfaces – ServletContextListener • contextInitialized/Destroyed(ServletContextEvent) – ServletContextAttributeListener • attributeAdded/Removed/Replaced(ServletContextAttributeEvent) – HttpSessionListener • sessionCreated/Destroyed(HttpSessionEvent) – HttpSessionAttributeListener • attributedAdded/Removed/Replaced(HttpSessionBindingEvent) Java Stream 97 Basic Steps for Implementing Event Listeners – Create a new class that implements the appropriate interface – Override the methods needed to respond to the events of interest – Obtain access to the important Web application objects • Servlet context • Servlet context attribute, its name and value • Session, session attribute name and value – Use these objects • e.g. Servlet context: getInitParameter(), setAttribute() and getAttribute() – Declare the listener • Configure listener and listener-class in web.xml – Provide any needed initialization parameters Java Stream 98 Example – A Session Counter Listener • Implement the session counter: Java Stream 99 Example – A Session Counter Listener (cont.) • Show session counter status: Java Stream 100 Example – A Session Counter Listener (cont.) • Configure the web.xml Java Stream