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

Similar documents
JAVA SERVLET. Server-side Programming PROGRAMMING

Session 20 Data Sharing Session 20 Data Sharing & Cookies

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

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

Servlets and JSP (Java Server Pages)

Java4570: Session Tracking using Cookies *

Advanced Internet Technology Lab # 6

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

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Module 4: SERVLET and JSP

Unit 4 - Servlet. Servlet. Advantage of Servlet

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

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

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

Generating the Server Response: HTTP Status Codes

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

AJP. CHAPTER 5: SERVLET -20 marks

Introduction. This course Software Architecture with Java will discuss the following topics:

Unit-4: Servlet Sessions:

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Chapter 10 Servlets and Java Server Pages

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Servlet Fudamentals. Celsina Bignoli

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

Servlets by Example. Joe Howse 7 June 2011

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

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

Advanced Internet Technology Lab # 4 Servlets

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Handling Cookies. Agenda

Handout 31 Web Design & Development

HTTP status codes. Setting status of an HTTPServletResponse

Generating the Server Response:

Construction d Applications Réparties / Master MIAGE

CE212 Web Application Programming Part 3

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

Servlet Basics. Agenda

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

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

Chapter 17. Web-Application Development

JdbcResultSet.java. import java.sql.*;

Chapter 29 Servlets: Bonus for Java Developers 1041

JAVA SERVLET. Server-side Programming INTRODUCTION

HTTP. HTTP HTML Parsing. Java

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

Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Java E-Commerce Martin Cooke,

JavaServer Pages (JSP)

Generating the Server Response: HTTP Response Headers

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Three hours UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE. Date: Friday 21 st May Time:

SERVLETS INTERVIEW QUESTIONS

Component Based Software Engineering

EXPERIMENT- 9. Login.html

Session 11. Calling Servlets from Ajax. Lecture Objectives. Understand servlet response formats

Session 8. Introduction to Servlets. Semester Project

Advanced Web Technology

Web Application Services Practice Session #2

Lab session Google Application Engine - GAE. Navid Nikaein

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

UNIT 1 SERVLET PROGRAMMING

The Structure and Components of

Chapter 2 How to structure a web application with the MVC pattern

11.1 Introduction to Servlets

Introduction. This course Software Architecture with Java will discuss the following topics:

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD

Session 10. Form Dataset. Lecture Objectives

Connecting the RISC Client to non-javascriptinterfaces

J2EE Web Development 13/1/ Application Servers. Application Servers. Agenda. In the beginning, there was darkness and cold.

Backend. (Very) Simple server examples

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

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

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

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

Servlet and JSP Review

Using Java servlets to generate dynamic WAP content

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Produced by. Web Development. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Web, HTTP and Web Caching

Integrating Servlets and JavaServer Pages Lecture 13

C24: Web API: Passing Arguments and Parsing Returns

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

INTERNET ENGINEERING. HTTP Protocol. Sadegh Aliakbary

COMP9321 Web Application Engineering

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.

Session 9. Introduction to Servlets. Lecture Objectives

Introduction to HTTP. Jonathan Sillito

Stateless -Session Bean

How to work with sessions and cookies

CIS 3952 [Part 2] Java Servlets and JSP tutorial

CS 5450 HTTP. Vitaly Shmatikov

1.264 Lecture 15. Web development environments: JavaScript Java applets, servlets Java (J2EE) Active Server Pages

Web based Applications, Tomcat and Servlets - Lab 3 -

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

Notes beforehand... For more details: See the (online) presentation program.

Questions and Answers

CHAPTER 8 NOTE TO READER:

Transcription:

Managing Cookies

Cookies Cookies are a general mechanism which server side applications can use to both store and retrieve information on the client side Servers send cookies in the HTTP response and browsers are expected to save and to send the cookie back to the Server whenever they make additional requests from the Server

Managing Cookies Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response: HttpServletResponse.addCookie(Cookie cookie) Cookie getter methods: getname(), getvalue(), getpath(), getdomain(), getmaxage, getsecure Cookie setter methods: setvalue(), setpath(), setdomain()

public class WelcomeBack extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getparameter("username"); if (user == null) { Cookie[] cookies = req.getcookies(); for (int i = 0 ; cookies!=null && i < cookies.length ; i++) { if (cookies[i].getname().equals("username")) user = cookies[i].getvalue(); } } else res.addcookie(new Cookie("username", user)); if (user!= null) { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); out.println("<html><body><h1>welcome Back " + user + </H1></html></body>"); } else { res.sendredirect("/dbi-servlets/login.html"); } } }

Session Management

HTTP is Stateless HTTP is a stateless protocol Individual requests are treated independently Without external support, one cannot tell whether an HTTP request is a part of a continuing interaction between the client and the server BUT some Web applications are stateful! Online stores that maintain a shopping cart Portals that remember your name and preferences

HTTP Sessions The solution: Client and Server transfer some unique data in the course of a session A session captures the notion of a continuous interaction between a server and a client For example, a series of requests and responses between IE and Tomcat with short intervals between them Session management should be oblivious to the end-user Session management should be efficient Is it reasonable to send the whole shopping cart upon every request to Amazon.com?

Session Supporting Servers A server that supports sessions holds the session-specific data in an internal data structure (session object) Upon the first request, the server initializes the session object and sends the client a unique key for this object During the session, the client attaches this key to every request to the server

Session Management Methods How is the session key shared between the client and the server? We will discuss two methods that Servlet containers support: 1. Session Cookies 2. URL rewriting

Session Cookies In the response to the first request of a session, the server puts a cookie, which contains a key to the session When the client sends subsequent requests, it also sends the cookie The browser sends the cookie as long as the requests are in the session bound (e.g. the same process) The server treats the cookie as valid as long as the requests are in the session bound (e.g. a short time period passed since the last request)

Session Cookies Session cookies are simply a special kind of cookies The time boundary of session cookies is based on the session and not on an explicit date This is the default expiration time Session data is kept on the server, while the session cookie holds only a key to this data

URL Rewriting Web browsers may refuse to save cookies Therefore, Servlet containers support session management through URL rewriting Instead of passing the session key in a cookie, the key is concatenated to the request URL Pages should contain dynamically created links for site navigation thus, users are oblivious to the session management

URL Rewriting request request (no cookie) id 2 Servlet Web browser 1 response id 1 Web server response Session read/write <HTML> GET servleturl;sessid=id 1 HTTP/1.0 <A HREF= servleturl;sessid=id 1 > </HTML>

Accessing the Session Data Session data is represented by the class HttpSession Use the methods getsesssion() or getsession(true) of the doxxx request to get the current HttpSession object, or to create one if it doesn t exist Use getsession(false) if you do not want to create a new session if no session exists

HttpSession Methods Session data is accessed in a hash-table fashion: - setattribute(string name,object value) - Where is this value stored? - Object getattribute(string name) More methods: - removeattribute, getattributenames - isnew, invalidate, getid - getcreationtime, getlastaccessedtime - getmaxinactiveinterval, setmaxinactiveinterval

GET /dbi-servlets/store HTTP/1.1 Accept: */* Host: localhost Connection: Keep-Alive HTTP/1.1 200 OK Set-Cookie: JSESSIONID=850173A82D7A7C66B28AF6F337AF73AD; Path=/dbi Content-Type: text/html Content-Length: 402 Server: Apache-Coyote/1.1 The first request to Servlet Response:

GET /dbi-servlets/store HTTP/1.1 Accept: */* Host: localhost Connection: Keep-Alive Cookie: JSESSIONID=850173A82D7A7C66B28AF6F337AF73AD HTTP/1.1 200 OK Content-Type: text/html Content-Length: 330 Server: Apache-Coyote/1.1 Next request to Servlet: Response:

Servlet URL Rewriting Use the following methods of the doxxx response object to rewrite URLs: - String encodeurl(string url) Use for HTML hyperlinks - String encoderedirecturl(string url) Use for HTTP redirections These methods contain the logic to determine whether the session ID needs to be encoded in the URL For example, if the request has a cookie, then url is returned unchanged Some servers implement the two methods identically

Example: <html><head><link rel="stylesheet" type="text/css" href="cartstyle.css"></head><body> Hello new visitor!<br><br> Your Shopping Cart:<ol><i> </i></ol> <form method="post action= "ShoppingCart;jsessionid=2409D7C062C6E32E2B4F28EAB1 36E7F8"> Add item:<input name="item" type="text"> <input type="submit" value="send"><br><br><input type="submit" value="empty Cart" name="clear"></form> </body></html>

Reference Representation and Management of Data on the Internet (67633), Yehoshua Sagiv, The Hebrew University - Institute of Computer Science.