Java Stream 1 11.1 Introduction 11.2 Servlet Overview and Architecture 11.2.1 Interface Servlet and the Servlet Life Cycle 11.2.2 HttpServlet Class 11.2.3.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
Dispatching, monitoring, filtering
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
HTTP HyperText Transfer Protocol Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
 2005 Pearson Education, Inc. All rights reserved Servlets.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and.
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class.
Java Servlets & Java Server Pages Lecture July 2013.
JSP Filters 23-Oct-15. JSP - FILTERS A filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Servlet Filters import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimerFilter implements Filter { /* J2EE v1.3 Filter.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
 2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Session Tracking Parts of this presentation was provided by SSE.
 2003 Prentice Hall, Inc. All rights reserved Deploying a Web Application ( may include.war )
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Servlets Outline 1 Introduction 2 Servlet Overview and Architecture 2.1 Interface Servlet and the Servlet Life Cycle 2.2 HttpServlet Class 2.3 HttpServletRequest.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Introduction to Servlets
Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Java Servlets.
Servlets Hits Counter 20-Jul-18.
Pre-assessment Questions
Chapter 24: Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
COP 4610L: Applications in the Enterprise Spring 2005
Chapter 30 - Servlets: Bonus for Java Developers
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Stream Introduction 11.2 Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest Interface HttpServletResponse Interface 11.3 Handling HTTP get Requests Setting Up the Apache Tomcat Server Deploying a Web Application 11.4 Handling HTTP get Requests Containing Data 11.5 Handling HTTP post Requests 11.6 Redirecting Requests to Other Resources 11.7 Session Tracking Cookies Session Tracking with HttpSession 11.8 Multi-Tier Applications: Using JDBC from a Servlet 11.9Servlet Context Servlet filter Web application listener Unit 09 - Servlet Programming

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

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 Web server –creates an HttpServletRequest object –passes it to the servlet’s service method HttpServletRequest object contains the request from the client HttpServletRequest Interface

Java Stream 8 HttpServletRequest Interface (Cont.)

Java Stream 9 HttpServletResponse Interface HttpServletResponse object contains the request from the client

Java Stream 10 Handling HTTP GET Requests GET request –Retrieve the content of a URL Example: WelcomeServlet –a servlet handles HTTP GET requests

Outline Java Stream 11 WelcomeServlet that responds to a simple HTTP get request. Lines 5-6 Line 9 Lines Line 16 Line 17 Lines // WelcomeServlet.java 2 // A simple servlet to process get requests. 3 package com.alliant.test.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet extends HttpServlet { // 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(); // send XHTML page to client // start XHTML document 22 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 25 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 29 " " ); // head section of document 32 out.println( " " ); 33 out.println( " A Simple Servlet Example " ); 34 out.println( " " ); 35 Import the javax.servlet and javax.servlet.http packages. Extends HttpServlet to handle HTTP get requests and HTTP post requests. Override method doGet to provide custom get request processing. Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client. Uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. Create the XHTML document by writing strings with the out object’s println method.

Outline Java Stream 12 WelcomeServlet that responds to a simple HTTP get request. Line // body section of document 37 out.println( " " ); 38 out.println( " Welcome to Servlets! " ); 39 out.println( " " ); // end XHTML document 42 out.println( " " ); 43 out.close(); // close stream to complete the page 44 } 45 } Closes the output stream, flushes the output buffer and sends the information to the client.

Outline Java Stream 13 HTML document in which the form’s action invokes WelcomeServlet through the alias welcome1 specified in web.xml. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Handling an HTTP Get Request Click the button to invoke the servlet

Java Stream 14 Setting Up the Apache Tomcat Server Download Tomcat (version ) – Define environment variables –JAVA_HOME –CATALINA_HOME Start the Tomcat server –CATALINA_HOME\bin\startup.bat Launch the Tomcat server – 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.)

Outline Java Stream 18 Deployment descriptor (web.xml) for the advjhtp1 Web application. Lines 5-37 Lines 8-11 Lines Lines Line 20 Lines Lines <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" 3 " Sample 10 Servlet Examples This is the Web application in which we 15 demonstrate our JSP and Servlet examples welcome A simple servlet that handles an HTTP get request com.alliant.test.servlets.WelcomeServlet Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. Element display-name specifies a name that can be displayed to the administrator of the server on which the Web application is installed. Element description specifies a description of the Web application that might be displayed to the administrator of the server. Element servlet describes a servlet.Element servlet-name is the name for the servlet. Element description specifies a description for this particular servlet. Element servlet-class specifies compiled servlet’s fully qualified class name.

Outline Java Stream 19 Deployment descriptor (web.xml) for the advjhtp1 Web application. Lines welcome1 34 /welcome Element servlet-mapping specifies servlet-name and url-pattern elements.

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

Java Stream 22 Handling HTTP GET Requests Containing Data Servlet WelcomeServlet2 –Responds to a get request that contains data

Outline Java Stream 23 WelcomeServlet2 responds to a get request that contains data. Line 16 1 // WelcomeServlet2.java 2 // Processing HTTP get requests containing data. 3 package com.alliant.test.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet2 extends HttpServlet { // 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" ); response.setContentType( "text/html" ); 19 PrintWriter out = response.getWriter(); // send XHTML document to client // start XHTML document 24 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 27 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 31 " " ); 32 The request object’s getParameter method receives the parameter name and returns the corresponding String value.

Outline Java Stream 24 WelcomeServlet2 responds to a get request that contains data. Line // head section of document 34 out.println( " " ); 35 out.println( 36 " Processing get requests with data " ); 37 out.println( " " ); // body section of document 40 out.println( " " ); 41 out.println( " Hello " + firstName + ", " ); 42 out.println( "Welcome to Servlets! " ); 43 out.println( " " ); // end XHTML document 46 out.println( " " ); 47 out.close(); // close stream to complete the page 48 } 49 } Uses the result of line 16 as part of the response to the client.

Outline Java Stream 25 HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Line <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Processing get requests with data Type your first name and press the Submit button Get the first name from the user.

Outline Java Stream 26 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.)

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

Outline Java Stream 29 WelcomeServlet3 responds to a post request that contains data. Lines // 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 { // 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" ); response.setContentType( "text/html" ); 19 PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document 24 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 27 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 31 " " ); 32 Define a doPost method to responds to post requests.

Outline Java Stream 30 WelcomeServlet3.java 33 // head section of document 34 out.println( " " ); 35 out.println( 36 " Processing post requests with data " ); 37 out.println( " " ); // body section of document 40 out.println( " " ); 41 out.println( " Hello " + firstName + ", " ); 42 out.println( "Welcome to Servlets! " ); 43 out.println( " " ); // end XHTML document 46 out.println( " " ); 47 out.close(); // close stream to complete the page 48 } 49 }

Outline Java Stream 31 HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Lines <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Handling an HTTP Post Request with Data Type your first name and press the Submit button Provide a form in which the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet3.

Outline Java Stream 32 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.)

Java Stream 34 Redirecting Requests to Other Resources Servlet RedirectServlet –Redirects the request to a different resource

Outline Java Stream 35 Redirecting requests to other resources. Line 16 Lines Line 21 Line 24 Lines // 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 { // 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" ); if ( location != null ) if ( location.equals( “alliant" ) ) 21 response.sendRedirect( " ); 22 else 23 if ( location.equals( "welcome1" ) ) 24 response.sendRedirect( "welcome1" ); // code that executes only if this servlet 27 // does not redirect the user to another page response.setContentType( "text/html" ); 30 PrintWriter out = response.getWriter(); 31 Obtains the page parameter from the request. Determine if the value is either “deitel” or “welcome1” Redirects the request to Redirects the request to the servlet WelcomeServlet. Output a Web page indicating that an invalid request was made if method sendRedirect is not called.

Outline Java Stream 36 Redirecting requests to other resources. 32 // start XHTML document 33 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 36 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 40 " " ); // head section of document 43 out.println( " " ); 44 out.println( " Invalid page " ); 45 out.println( " " ); // body section of document 48 out.println( " " ); 49 out.println( " Invalid page requested " ); 50 out.println( " <a href = " + 51 "\"servlets/RedirectServlet.html\">" ); 52 out.println( "Click here to choose again " ); 53 out.println( " " ); // end XHTML document 56 out.println( " " ); 57 out.close(); // close stream to complete the page 58 } 59 }

Outline Java Stream 37 RedirectServlet.html document to demonstrate redirecting requests to other resources. Lines Lines <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Redirecting a Request to Another Site Click a link to be redirected to the appropriate page Welcome servlet Provide hyperlinks that allow the user to invoke the servlet RedirectServlet.

Java Stream 38 Redirecting Requests to other Resources (Cont.)

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

Outline Java Stream 41 Storing user data on the client computer with cookies. Lines Line 28 Line 29 Line 30 Line 32 1 // CookieServlet.java 2 // Using cookies to store data on the client computer. 3 package com.alliant.test.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import java.util.*; 9 10 public class CookieServlet extends HttpServlet { 11 private final Map books = new HashMap(); // initialize Map books 14 public void init() 15 { 16 books.put( "C", " " ); 17 books.put( "C++", " " ); 18 books.put( "Java", " " ); 19 books.put( "VB6", " " ); 20 } // receive language selection and send cookie containing 23 // recommended book to the client 24 protected void doPost( HttpServletRequest request, 25 HttpServletResponse response ) 26 throws ServletException, IOException 27 { 28 String language = request.getParameter( "language" ); 29 String isbn = books.get( language ).toString(); 30 Cookie cookie = new Cookie( language, isbn ); response.addCookie( cookie ); // must precede getWriter 33 response.setContentType( "text/html" ); 34 PrintWriter out = response.getWriter(); 35 Method init populates books with four key/value pair of books. Uses method getParameter to obtain the user’s language selection. Gets the ISBN number for the selected language from books. Creates a new Cookie object, using the language and isbn values as the cookie name and cookie value, respectively. Adds the cookie to the response with method addCookie of interface HttpServletResponse.

Outline Java Stream 42 Storing user data on the client computer with cookies. 36 // send XHTML page to client // start XHTML document 39 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 42 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 46 " " ); // head section of document 49 out.println( " " ); 50 out.println( " Welcome to Cookies " ); 51 out.println( " " ); // body section of document 54 out.println( " " ); 55 out.println( " Welcome to Cookies! You selected " + 56 language + " " ); out.println( " <a href = " + 59 "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" + 60 "Click here to choose another language " ); out.println( " " + 63 "Click here to get book recommendations " ); 64 out.println( " " ); // end XHTML document 67 out.println( " " ); 68 out.close(); // close stream 69 } 70

Outline Java Stream 43 Storing user data on the client computer with cookies. Line // read cookies from client and create XHTML document 72 // containing recommended books 73 protected void doGet( HttpServletRequest request, 74 HttpServletResponse response ) 75 throws ServletException, IOException 76 { 77 Cookie cookies[] = request.getCookies(); // get cookies response.setContentType( "text/html" ); 80 PrintWriter out = response.getWriter(); // start XHTML document 83 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 86 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 90 " " ); // head section of document 93 out.println( " " ); 94 out.println( " Recommendations " ); 95 out.println( " " ); // body section of document 98 out.println( " " ); // if there are any cookies, recommend a book for each ISBN 101 if ( cookies != null && cookies.length != 0 ) { 102 out.println( " Recommendations " ); 103 out.println( " " ); 104 Retrieves the cookies from the client using HttpServletRequest method getCookies, which returns an array of Cookie objects.

Outline Java Stream 44 Storing user data on the client computer with cookies. 105 // get the name of each cookie 106 for ( int i = 0; i < cookies.length; i++ ) 107 out.println( cookies[ i ].getName() " How to Program. ISBN#: " cookies[ i ].getValue() + " " ); out.println( " " ); 112 } 113 else { // there were no cookies 114 out.println( " No Recommendations " ); 115 out.println( " You did not select a language. " ); 116 } out.println( " " ); // end XHTML document 121 out.println( " " ); 122 out.close(); // close stream 123 } 124 }

Outline Java Stream 45 CookieSelectLan guage.html document for selecting a programming language and posting the data to the CookieServlet. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Using Cookies Select a programming language: <input type = "radio" name = "language" 18 value = "C" />C <input type = "radio" name = "language" 21 value = "C++" />C <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java <input type = "radio" name = "language" 28 value = "VB6" />VB

Outline Java Stream 46 CookieSelectLan guage.html document for selecting a programming language and posting the data to the CookieServlet. Program output

Outline Java Stream 47 CookieSelectLan guage.html document for selecting a programming language and posting the data to the CookieServlet. Program output

Java Stream 48 Cookies (Cont.)

Java Stream 49 Cookies (Cont.) (Part 1 of 2) Important methods of class Cookie.

Java Stream 50 Cookies (Cont.)

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");

Outline Java Stream 54 Maintaining state information with HttpSession objects. Line 28 Line 32 Line 35 1 // SessionServlet.java 2 // Using HttpSession to maintain client state information. 3 package com.deitel.test.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import java.util.*; 9 10 public class SessionServlet extends HttpServlet { 11 private final Map books = new HashMap(); // initialize Map books 14 public void init() 15 { 16 books.put( "C", " " ); 17 books.put( "C++", " " ); 18 books.put( "Java", " " ); 19 books.put( "VB6", " " ); 20 } // receive language selection and create HttpSession object 23 // containing recommended book for the client 24 protected void doPost( HttpServletRequest request, 25 HttpServletResponse response ) 26 throws ServletException, IOException 27 { 28 String language = request.getParameter( "language" ); // Get the user's session object. 31 // Create a session (true) if one does not exist. 32 HttpSession session = request.getSession( true ); // add a value for user's choice to session 35 session.setAttribute( language, books.get( language ) ); Gets the user’s language selection. Uses method getSession of interface HttpServletRequest to obtain the HttpSession object for the client. Uses setAttribute to put the language and the corresponding recommended book’s ISBN number into the HttpSession object.

Outline Java Stream 55 Maintaining state information with HttpSession objects. Line 64 Line response.setContentType( "text/html" ); 38 PrintWriter out = response.getWriter(); // send XHTML page to client // start XHTML document 43 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 46 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 50 " " ); // head section of document 53 out.println( " " ); 54 out.println( " Welcome to Sessions " ); 55 out.println( " " ); // body section of document 58 out.println( " " ); 59 out.println( " Welcome to Sessions! You selected " + 60 language + ". " ); // display information about the session 63 out.println( " Your unique session ID is: " + 64 session.getId() + " " ); out.println( 67 "This " + ( session.isNew() ? "is" : "is not" ) + 68 " a new session " ); 69 Uses HttpSession method getID to obtain the session’s unique ID number. Determines whether the session is new or already exists with method isNew.

Outline Java Stream 56 Fig Maintaining state information with HttpSession objects. Line 71 Line 74 Line 77 Line out.println( "The session was created at: " + 71 new Date( session.getCreationTime() ) + " " ); out.println( "You last accessed the session at: " + 74 new Date( session.getLastAccessedTime() ) + " " ); out.println( "The maximum inactive interval is: " + 77 session.getMaxInactiveInterval() + " seconds " ); out.println( " <a href = " + 80 "\"servlets/SessionSelectLanguage.html\">" + 81 "Click here to choose another language " ); out.println( " " + 84 "Click here to get book recommendations " ); 85 out.println( " " ); // end XHTML document 88 out.println( " " ); 89 out.close(); // close stream 90 } // read session attributes and create XHTML document 93 // containing recommended books 94 protected void doGet( HttpServletRequest request, 95 HttpServletResponse response ) 96 throws ServletException, IOException 97 { 98 // Get the user's session object. 99 // Do not create a session (false) if one does not exist. 100 HttpSession session = request.getSession( false ); // get names of session object's values 103 Enumeration valueNames; 104 Obtains the time at which the session was created with method getCreationTime. Obtains the time at which the session was last accessed with method getLastAccessedTime. Uses method getMaxInactiveInterval to obtain the maximum amount of time that an HttpSession object can be inactive before the servlet container discards it. Obtains the HttpSession object for the client with method getSession.

Outline Java Stream 57 Maintaining state information with HttpSession objects. Line if ( session != null ) 106 valueNames = session.getAttributeNames(); 107 else 108 valueNames = null; PrintWriter out = response.getWriter(); 111 response.setContentType( "text/html" ); // start XHTML document 114 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 121 " " ); // head section of document 124 out.println( " " ); 125 out.println( " Recommendations " ); 126 out.println( " " ); // body section of document 129 out.println( " " ); if ( valueNames != null && 132 valueNames.hasMoreElements() ) { 133 out.println( " Recommendations " ); 134 out.println( " " ); String name, value; 137 Uses HttpSession method getAttributeNames to retrieve an Enumeration of the attribute names.

Outline Java Stream 58 Maintaining state information with HttpSession objects. Line // get value for each name in valueNames 139 while ( valueNames.hasMoreElements() ) { 140 name = valueNames.nextElement().toString(); 141 value = session.getAttribute( name ).toString(); out.println( name + " How to Program. " "ISBN#: " + value + " " ); 145 } out.println( " " ); 148 } 149 else { 150 out.println( " No Recommendations " ); 151 out.println( " You did not select a language. " ); 152 } out.println( " " ); // end XHTML document 157 out.println( " " ); 158 out.close(); // close stream 159 } 160 } Invokes method getAttribute of HttpSession to retrieve the ISBN of a book from the HttpSession object.

Outline Java Stream 59 SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Using Sessions Select a programming language: <input type = "radio" name = "language" 18 value = "C" />C <input type = "radio" name = "language" 21 value = "C++" />C <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java <input type = "radio" name = "language" 28 value = "VB6" />VB

Outline Java Stream 60 SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output

Outline Java Stream 61 SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output

Outline Java Stream 62 SessionSelectLa nguage.html document for selecting a programming language and posting the data to the SessionServlet. Program output

Outline Java Stream 63 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.)

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

Outline Java Stream 66 Multi-tier Web- based survey using XHTML, servlets and JDBC. Lines Line 21 Lines Lines // SurveyServlet.java 2 // A Web-based survey that uses JDBC from a servlet. 3 package com.alliant.test.servlets; 4 5 import java.io.*; 6 import java.text.*; 7 import java.sql.*; 8 import javax.servlet.*; 9 import javax.servlet.http.*; public class SurveyServlet extends HttpServlet { 12 private Connection connection; 13 private PreparedStatement updateVotes, totalVotes, results; // set up database connection and prepare SQL statements 16 public void init( ServletConfig config ) 17 throws ServletException 18 { 19 // attempt database connection and create PreparedStatements 20 try { 21 Class.forName( "com.mysql.jdbc.Driver" ); 22 connection = DriverManager.getConnection( 23 "jdbc:mysql://localhost:3306/test" ); // PreparedStatement to add one to vote total for a 26 // specific animal 27 updateVotes = 28 connection.prepareStatement( 29 "UPDATE surveyresults SET votes = votes + 1 " + 30 "WHERE id = ?" 31 ); 32 Servlets are initialized by overriding method init. Loads the database driver. Attempt to open a connection to the animalsurvey database. Create PreparedStatement updateVotes object.

Outline Java Stream 67 Multi-tier Web- based survey using XHTML, servlets and JDBC. Lines // PreparedStatement to sum the votes 34 totalVotes = 35 connection.prepareStatement( 36 "SELECT sum( votes ) FROM surveyresults" 37 ); // PreparedStatement to obtain surveyoption table's data 40 results = 41 connection.prepareStatement( 42 "SELECT surveyoption, votes, id " + 43 "FROM surveyresults ORDER BY id" 44 ); 45 } // for any exception throw an UnavailableException to 48 // indicate that the servlet is not currently available 49 catch ( Exception exception ) { 50 exception.printStackTrace(); 51 throw new UnavailableException(exception.getMessage()); 52 } } // end of init method // process survey response 57 protected void doPost( HttpServletRequest request, 58 HttpServletResponse response ) 59 throws ServletException, IOException 60 { 61 // set up response to client 62 response.setContentType( "text/html" ); 63 PrintWriter out = response.getWriter(); 64 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 65 Create PreparedStatement totalVotes and results objects.

Outline Java Stream 68 Multi-tier Web- based survey using XHTML, servlets and JDBC. Lines Lines Lines Lines // start XHTML document 67 out.println( " " ); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 70 "XHTML 1.0 Strict//EN\" \" "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); out.println( 74 " " ); // head section of document 77 out.println( " " ); // read current survey response 80 int value = 81 Integer.parseInt( request.getParameter( "animal" ) ); // attempt to process a vote and display current results 84 try { // update total for current surevy response 87 updateVotes.setInt( 1, value ); 88 updateVotes.executeUpdate(); // get total of all survey responses 91 ResultSet totalRS = totalVotes.executeQuery(); 92 totalRS.next(); 93 int total = totalRS.getInt( 1 ); // get results 96 ResultSet resultsRS = results.executeQuery(); 97 out.println( " Thank you! " ); 98 out.println( " " ); 99 Obtain the survey response 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.

Outline Java Stream 69 Multi-tier Web- based survey using XHTML, servlets and JDBC. 100 out.println( " " ); 101 out.println( " Thank you for participating." ); 102 out.println( " Results: " ); // process results 105 int votes; while ( resultsRS.next() ) { 108 out.print( resultsRS.getString( 1 ) ); 109 out.print( ": " ); 110 votes = resultsRS.getInt( 2 ); 111 out.print( twoDigits.format( 112 ( double ) votes / total * 100 ) ); 113 out.print( "% responses: " ); 114 out.println( votes ); 115 } resultsRS.close(); out.print( "Total responses: " ); 120 out.print( total ); // end XHTML document 123 out.println( " " ); 124 out.close(); 125 } // if database exception occurs, return error page 128 catch ( SQLException sqlException ) { 129 sqlException.printStackTrace(); 130 out.println( " Error " ); 131 out.println( " " ); 132 out.println( " Database error occurred. " ); 133 out.println( "Try again later. " ); 134 out.close();

Outline Java Stream 70 Multi-tier Web- based survey using XHTML, servlets and JDBC. Lines } } // end of doPost method // close SQL statements and database when servlet terminates 140 public void destroy() 141 { 142 // attempt to close statements and database connection 143 try { 144 updateVotes.close(); 145 totalVotes.close(); 146 results.close(); 147 connection.close(); 148 } // handle database exceptions by returning error to client 151 catch( SQLException sqlException ) { 152 sqlException.printStackTrace(); 153 } 154 } // end of destroy method 155 } Method destroy closes each PreparedStatement and database connection.

Outline Java Stream 71 Survey.html document that allows users to submit survey responses to SurveyServlet. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Survey What is your favorite pet? <input type = "radio" name = "animal" 19 value = "1" />Dog 20 <input type = "radio" name = "animal" 21 value = "2" />Cat 22 <input type = "radio" name = "animal" 23 value = "3" />Bird 24 <input type = "radio" name = "animal" 25 value = "4" />Snake 26 <input type = "radio" name = "animal" 27 value = "5" checked = "checked" />None

Outline Java Stream 72 Survey.html document that allows users to submit survey responses to SurveyServlet.

Java Stream 73 Multi-Tier Applications: Using JDBC from a Servlet (Cont.)

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!”

Outline Java Stream 77 HelloWorldGraphics that responds to with a gif graphic 1 // HelloWorldGraphics.java 2 // A simple servlet to generate an on the fly image. 3 package com.alliant.test.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import Acme.JPM.Encoders.GifEncoder; 9 public class HelloWorldGraphics extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) 12 throws ServletException, IOException { 13 ServletOutputStream out = res.getOutputStream(); // binary output! Frame frame = null; 12 Graphics g = null; 13 try { 14 // Create an unshown frame 15 frame = new Frame(); 16 frame.addNotify(); 17 // Get a graphics region, using the Frame 18 Image image = frame.createImage(400, 60); 19 g = image.getGraphics(); 20 // Draw "Hello World!" to the off-screen graphics context 21 g.setFont(new Font("Serif", Font.ITALIC, 48)); 22 g.drawString("Hello World!", 10, 50); 23 // Encode the off-screen image into a GIF and send it to the client 24 res.setContentType("image/gif"); 25 GifEncoder encoder = new GifEncoder(image, out); 26 encoder.encode(); 27 } 28 finally { 29 // Clean up resources 30 if (g != null) g.dispose(); 31 if (frame != null) frame.removeNotify(); 32 } 35 } 36 }

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:

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

Outline Java Stream 89 BannedAccessFilter.j ava 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. */ 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; }

Outline Java Stream 90 BannedAccessFilter.j ava if (isBanned) { showWarning(response, bannedSite); } else { chain.doFilter(request,response); } /** 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); }

Outline Java Stream 91 BannedAccessFilter.j ava 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); } // 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";

Outline Java Stream 92 BannedAccessFilter.j ava out.println (docType + " \n" + " Access Prohibited \n" + " \n" + " Access Prohibited \n" + "Sorry, access from or via " + bannedSite + "\n" + "is not allowed.\n" + " "); }

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