Session 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing

Similar documents
Session 20 Data Sharing Session 20 Data Sharing & Cookies

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

JAVA SERVLET. Server-side Programming PROGRAMMING

Servlets and JSP (Java Server Pages)

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Java4570: Session Tracking using Cookies *

Servlet Fudamentals. Celsina Bignoli

Servlets. An extension of a web server runs inside a servlet container

Chapter 10 Servlets and Java Server Pages

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

AJP. CHAPTER 5: SERVLET -20 marks

Unit 5 JSP (Java Server Pages)

Vendor: SUN. Exam Code: Exam Name: Sun Certified Web Component Developer for J2EE 5. Version: Demo

Table of Contents. Introduction... xxi

More JSP. Advanced Topics in Java. Khalid Azim Mughal Version date: ATIJ More JSP 1/42

Unit 4 - Servlet. Servlet. Advantage of Servlet

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Unraveling the Mysteries of J2EE Web Application Communications

Java E-Commerce Martin Cooke,

CS506 Web Design & Development Final Term Solved MCQs with Reference

Module 3 Web Component

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

Fast Track to Java EE

Questions and Answers

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

SERVLETS INTERVIEW QUESTIONS

Lecture 9a: Sessions and Cookies

CIS 455 / 555: Internet and Web Systems

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

Java.. servlets and. murach's TRAINING & REFERENCE 2ND EDITION. Joel Murach Andrea Steelman. IlB MIKE MURACH & ASSOCIATES, INC.

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product.

Introduction to JSP and Servlets Training 5-days

1. Introduction. 2. Life Cycle Why JSP is preferred over Servlets? 2.1. Translation. Java Server Pages (JSP) THETOPPERSWAY.

Exam Questions 1Z0-895

CS105 Perl: Perl CGI. Nathan Clement 24 Feb 2014

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Advanced Internet Technology Lab # 4 Servlets

One application has servlet context(s).

About the Authors. Who Should Read This Book. How This Book Is Organized

Programming on the Web(CSC309F) Tutorial 9: JavaServlets && JDBC TA:Wael Abouelsaadat

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Oracle 10g: Build J2EE Applications

Construction d Applications Réparties / Master MIAGE

Session 8. Introduction to Servlets. Semester Project

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

User Manual. Admin Report Kit for IIS 7 (ARKIIS)

Java SE7 Fundamentals

Java Enterprise Edition

IBM. Enterprise Application Development with IBM Web Sphere Studio, V5.0

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Server-side computing

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

CS1004: Intro to CS in Java, Spring 2005

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

ive JAVA EE C u r r i c u l u m

RQs + PEs: More Servlets

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

First Simple Interactive JSP example

Chapter 4: Writing Classes

Part I: Communication and Networking

Handling Cookies. Agenda

Data Management in Application Servers. Dean Jacobs BEA Systems

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

IT6503 WEB PROGRAMMING. Unit-I

Module 4: SERVLET and JSP

This module is only available for Wicket viewer, not the REST API.

Advanced Web Technology

Managing State. Chapter 13

SNS COLLEGE OF ENGINEERING, Coimbatore

Model View Controller (MVC)

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

CSC309: Introduction to Web Programming. Lecture 10

Java E-Commerce Martin Cooke,

Fast Track to Java EE 5 with Servlets, JSP & JDBC

BIG-IP Access Policy Manager : Portal Access. Version 12.1

Handling Cookies. For live Java EE training, please see training courses at

Handout 31 Web Design & Development

JSP. Common patterns

JSP - SYNTAX. Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

WebSphere Application Server V7: Session Management

********************************************************************

WEB SECURITY: WEB BACKGROUND

Chapter 17. Web-Application Development

Developing Applications with Java EE 6 on WebLogic Server 12c

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

The Operating System. Chapter 6

UNIT - III. Every element in a document tree refers to a Node object. Some nodes of the tree are

Component Based Software Engineering

UNIT I. A protocol is a precise set of rules defining how components communicate, the format of addresses, how data is split into packets

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Configuring Stickiness

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Introduction to Programming Using Java (98-388)

An excellent explanation of how web browsers work:

Transcription:

Session 9 Data Sharing & Cookies 1 Reading Reading & Reference Chapter 5, pages 185-204 Reference http state management www.ietf.org/rfc/rfc2109.txt?number=2109 2 3/1/2010 1

Lecture Objectives Understand how the Web Container uses cookies to store server data so that it is available to separate servlet executions Know how to use server shared objects to store state information Understand the scope differences for ServletContext and Session objects Understand the ways in which a session object is implemented by the Web container Understand how the Web container uses threads to match user requests to servlets 3 When Do You Need to Share Data? Among servlets cooperating on an application Among servlets cooperating to satisfy the requests from a single user (e.g., shopping cart) Usually on the same workstation and browser 4 3/1/2010 2

Servlet Data Sharing The Http protocol is stateless, so your servlet only responds to a single request Question: Where do you store data from your servlet when the data is needed for multiple requests? Answer: Anywhere you can Approaches: browser side and server side Browser side state data Server side state data ServletContext Browser (cookies and hidden form fields) Servlet HttpSession HttpServletRequest 5 Browser Side Storage request response Wb Web Container ti Data stored on the browser is included in the response object and returned to the servlet through the request object What data is transmitted through http? Form data set Cookies 6 3/1/2010 3

Implement a counter using: Hidden form field Cookies ServletContext Session Data Sharing Example The servlet stores a counter that is updated whenever a user sends another request 7 Browser Storage: Hidden Form Fields Store the data in a form field generated by your servlet. lt The hidden form field is not displayed in the browser window <form action="http://localhost:8080/codecse336/datasharing"> <input type = "hidden" name = "hiddencounter" value = "1"> <input type="submit"> </form> The value of hiddencounter is 1 the first time the servlet is invoked 8 3/1/2010 4

Example Hidden Form Field Code Servlet Code Fragment String scounter = request.getparameter("hiddencounter"); if (scounter!= null) hffcount = Integer.parseInt(sCounter) else hffcount = 0; Counter is updated and added to html hffcount++; out.println("<form action=\ http://localhost:8080/codecse336/datasharing\ >"); out.println("<input type = \"hidden\" name = \"hiddencounter\" value = \"" + hffcount + "\">"); out.println("<input type=\"submit\">"); out.println("</form>"); out.println("<p>hidden form field variable - "); out.println(hscount + "</p>"); 9 Features Hidden Form Fields Visible in the html, not visible on the displayed page Only available as long as the html page is alive in the browser Only associated with a browser in a computer There are some hidden form fields in your Oracle project but you can remove them 10 3/1/2010 5

Cookies A cookie is a small amount of information sent by the server to the browser that can later be read back from the browser Usually contained in a Cookies folder * Typical cookie Adc1 11780 NY56 078 @NY ISP ISP accuweather.com/ 0 3337461760 29399690 101711582429393656 Adc2 5 1 40.88-73.16 SAINT JAMES... 11 Cookie Process request response Web Container 1. Your servlet sets a cookie by including it in the response 2. Your browser stores the cookie In your cookies directory on your hard disk 3. Your browser sends the cookie every time a request is made to a server in your domain 12 3/1/2010 6

Cookies Cookies set by a server are returned to the server each time the browser accesses a corresponding page on the server Cookies sent by a browser are sent based on the server name Cookies are included in the http header info Most browsers support cookies (up to 20 per site and up to 4KB per cookie) Multiple cookies can have the same name Pages with cookies sent to a client are not currently cached in either Http 1.0 or 1.1 However, users can turn cookies off 13 Purposes Session information Site recognition sometimes instead of an ID/Password Site customization Focused advertising 14 3/1/2010 7

Cookie Class Methods setcomment setdomain allows patterns setmaxage in seconds, a value of 1 indicates that the cookie will exist until browser shutdown setpath must include the servlet setter path setsecure indicates it must be sent secure (e.g., SSL) setvalue() There are limitations on possible characters the cookie can contain setversion() Version 0 or Version 1 Plus corresponding get methods 15 To send a cookie, Cookie Access Style Instantiate a Cookie object Set any attributes (e.g., domain, duration) Send the cookie (addcookie method in response) note the standard term for this is set the cookie To get information from a cookie, Retrieve all the cookies from the user's request Find the cookie or cookies with the name that t you are interested in, using standard programming techniques Get the values of the cookies that you found 16 3/1/2010 8

Cookies Summary Single system data sharing - Usable on any system that stores the server s cookie file Extra data traffic for all requests to the server (from that browser) Unreliable user may have cookies disabled 17 Server Side Storage request Web Container Servlet 1 Servlet 1 Server object Servlet 2 Data stored on the server is usually contained in an object visible to the servlet (although occasionally server side data is stored in instance variables of the servlet object) To access the shared object, you need to obtain a reference (handle) to the object Objects for sharing Even the servlet is an HttpServletRequest object that you can use to ServletContext share information Session Other predefined and private objects 18 3/1/2010 9

Shared Objects attribute An attribute is a name/value pair Who can see the shared object? How long does the shared attribute last? 19 ServletContext Actually, an interface to the Web container, but you can think of it as a shared object used to store data available to all servlets in the Web application There is one ServletContext per Web application You can obtain a reference to the ServletContext object in many ways (e.g., through h a call to the getservletcontext method of HttpServlet) 20 3/1/2010 10

Using the ServletContext Includes methods for getting and setting an attribute (name/value pair) as if the ServletContext t t were a HashTable or a Map Object getattribute(string) void setattribute(string, Object) Enumeration getattributenames() How would you use the ServletContext to store a value (e.g., the access counter)? The name/value pairs are of type String/Object 21 Example Counter with ServletContext The servlet uses the ServletContext to store the access count 22 3/1/2010 11

Example ServletContext Code Get a handle to the ServletContext... ServletContext sc = this.getservletcontext(); Integer c = (Integer) sc.getattribute("counter"); if (c!= null) sccount = c.intvalue(); else sccount = 0; sccount++; sc.setattribute("counter", t t " new Integer(scCount)); t)) out.println("<p>servletcontext variable - "); out.println(sccount + "</p>"); 23 Shared Objects attribute The shared objects are referred to as scopes The shared scopes are contained in other objects For example, the request object contains a scope HttpServletRequest contenttype method etc. 24 3/1/2010 12

Why Do We Need a Session? The ServletContext object allows you to store servlet data beyond a single request, but: The life of the ServletContext object might be too long You might want to limit the sharing to one user For example, data for a shopping application (a shopping cart) has a life that is only as long as the user is shopping and the shopping cart is only visible to servlet executions for that user 25 Session Object The Web container provides (and manages) session objects You can store information in a session object using name-value pairs, but the session object only exists for the life of the session A session usually corresponds to one user, who may visit a site many times where the interval between visits is small Note that there are many session objects, but only one associated with a single computer/browser How does the Web Container identify a user? 26 3/1/2010 13

You get a handle to the session with a call to request.getsession() You access the session data through the session tracking parts of the Session API Session Tracking Returns an enumeration Session getattribute(string) setattribute(string, Object) getattributenames() removeattribute(string) Notice that the name/value pair is of type String/Object 27 Session Life Cycle API You can set the duration of a session (e.g., 20 minutes) Or you can invalidate the session when you are finished (e.g., when the user logs out) Session invalidate() isnew() getcreationtime() getlastaccessedtime() setmaxinactiveinterval(int) 28 3/1/2010 14

Steps in Session Management Request a session object. This can be either: A session object that was previously created and may contain data inserted by another servlet A new session object when there is no existing session object matching this user Store information in the session object Invalidate the session - or allow the session to time out when maxinactiveinterval (time in seconds) is exceeded setmaxinactiveinterval(int interval) Objects attached to the session can receive notification when they are unbound through a listener interface 29 Obtaining a Session Use the getsession method of HttpServletRequest Returns an HttpSession object When the parameter of getsession is true or there is no parameter, a new session object is created, if it does not already exist getsession(false) will return null if there is no session HttpSession session = request.getsession(true); 30 3/1/2010 15

Example Counter with Session The servlet uses the Session to store the access count 31 Session Counter HttpSession hs = request.getsession(true); c = (Integer) hs.getattribute("counter"); getattribute returns an Object, which we cast to Integer if (c!= null) hscount = c.intvalue(); else hscount = 0; hscount++; hs.setattribute("counter", new Integer(hsCount)); out.println("<p>session counter - "); out.println(hscount + "</p>"); 32 3/1/2010 16

How Do The Counters Differ? Visibility Different browsers? Different computers? Lifetime Servlet? Web application? This defines the scope of the object 33 Server Session Recognition Session object is managed by the Web Container Implementation technique depends on the Web container implementation (and browser settings), and includes: Hidden form fields URL Rewriting Cookies Session data access and storage is usually implemented by the Web Container, but you should understand what is done Used most often 34 3/1/2010 17

Session Identifier Strategies Http request Browser Server response includes a session identifier embedded in the HTML - or the Server sets the cookie Web Container Subsequent links or form submissions include the session identifier 35 URL Rewriting The session identifier is included in all relevant URLs in the HTML sent from the server to the browser Subsequent links to the URL include the precoded session data HTML Example: http://server:port/servlet/rewriter?sessionid=123 Technique only works for dynamically generated pages Potential for errors 36 3/1/2010 18

URL Rewriting Servlet Example Session identifier is included in all URLs linking back to the server Requested by your code, but inserted by the Java library code All URLs emitted by a servlet should be wrapped with this method call out.println( <td> + <h3>what We re Reading</h3> + <p> + In <em><a href=\ + res.encodeurl( /CodeCSE336/b?bookId=203 ) + \ >Servlets</a></em> +... 37 Servlet Execution How does the Web Container handle simultaneous requests to a servlet? 3 choices MyServlet instance Servlet Servlet Threads that Servlet invoke myservlet MyServlet instance MyServlet instance Is it safe for multiple threads to invoke myservlet? 38 3/1/2010 19

Multi-threaded Servlet Access request Web Container request request request thread thread thread servlet thread 39 Synchronization It is possible for 2 or more threads to have access to the same object (or primitive) Most operations are not indivisible (modifications require multiple machine instructions), so corruption can result (called a race condition) To avoid simultaneous access to a shared object, you synchronize access to the object Synchronized method Synchronized block Single Thread Model 40 3/1/2010 20

Synchronized Methods A synchronized keyword in a method signature declares that access to a method be synchronized public synchronized void transfer(int from, int to, int amount) When a thread calls a synchronized method of an object, the object becomes locked it is guaranteed that the method will complete before another thread can execute any synchronized method on the same object Other threads can call unsynchronized methods 41 Synchronized Code Block Blocks of code can be synchronized, as can methods The object referenced in the synchronized statement is locked Example synchronized (this) {... } In a servlet, lt this locks access to the servlet object (e.g., access to the servlet instance variables) 42 3/1/2010 21

Single Thread Model Your servlet can implement the (empty) SingleThreadModel interface The server guarantees that no two threads will execute concurrently in the servlet s service method Usually implemented with a pool of servlet instances (Web container configuration) Much better to synchronize access than to use the SingleThreadModel Why? 43 Did You Satisfy the Lecture Objectives? Understand how the Web Container usees cookies to store server data so that it is available to separate servlet lt executions Know how to use server shared objects to store state information Understand the scope differences for ServletContext and Session objects Understand the ways in which a session object is implemented by the Web container Understand how the Web container uses threads to match user requests to servlets 44 3/1/2010 22