SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
© 2010 Marty Hall
S i T kiSession Tracking
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.3
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Agenda
• Implementing session tracking from scratch
• Using basic session tracking
• Understanding the session-tracking API
Diff ti ti b t d b• Differentiating between server and browser
sessions
• Encoding URLs• Encoding URLs
• Storing immutable objects vs. storing
mutable objectsmutable objects
• Tracking user access counts
• Accumulating user purchasesg p
• Implementing a shopping cart
• Building an online store5
© 2010 Marty Hall
Overview
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.6
Session Tracking
and E-Commerceand E-Commerce
• Why session tracking?
– When clients at on-line store add item to their shopping
cart, how does server know what’s already in cart?
– When clients decide to proceed to checkout how can– When clients decide to proceed to checkout, how can
server determine which previously created cart is theirs?
7
Dilbert used with permission of United Syndicates Inc.
Rolling Your Own Session
Tracking: CookiesTracking: Cookies
• Idea: associate cookie with data on server
String sessionID = makeUniqueString();
HashMap sessionInfo = new HashMap();
HashMap globalTable = findTableStoringSessions();
globalTable.put(sessionID, sessionInfo);
Cookie sessionCookie =
new Cookie("JSESSIONID", sessionID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
Still to be done:• Still to be done:
– Extracting cookie that stores session identifier
– Setting appropriate expiration time for cookieSetting appropriate expiration time for cookie
– Associating the hash tables with each request
– Generating the unique session identifiers8
Rolling Your Own Session
Tracking: URL-RewritingTracking: URL-Rewriting
• Idea
– Client appends some extra data on the end of each URL
that identifies the session
– Server associates that identifier with data it has stored– Server associates that identifier with data it has stored
about that session
– E.g., http://host/path/file.html;jsessionid=1234
• Advantage
– Works even if cookies are disabled or unsupported
Di d t• Disadvantages
– Must encode all URLs that refer to your own site
All pages must be dynamically generated– All pages must be dynamically generated
– Fails for bookmarks and links from other sites
9
Rolling Your Own Session
Tracking: Hidden Form FieldsTracking: Hidden Form Fields
• Idea:
<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">
• Advantage
– Works even if cookies are disabled or unsupported
• Disadvantages
– Lots of tedious processing
– All pages must be the result of form submissions
10
© 2010 Marty Hall
The Java Session-The Java Session-
Tracking APIg
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.11
Session Tracking Basics
• Access the session object
– Call request.getSession to get HttpSession object
• This is a hashtable associated with the user
• Look up information associated with a• Look up information associated with a
session.
– Call getAttribute on the HttpSession object, cast theg p j ,
return value to the appropriate type, and check whether
the result is null.
Store information in a session• Store information in a session.
– Use setAttribute with a key and a value.
• Discard session data• Discard session data.
– Call removeAttribute discards a specific value.
– Call invalidate to discard an entire session.12
Session Tracking Basics:
Sample CodeSample Code
HttpSession session = request.getSession();
synchronized(session) {synchronized(session) {
SomeClass value =
(SomeClass)session.getAttribute("someID");
if (value null) {if (value == null) {
value = new SomeClass(...);
session.setAttribute("someID", value);
}}
doSomethingWith(value);
}
• Do not need to call setAttribute again (after modifying value) if the modified
value is the same object But if value is immutable modified value will be avalue is the same object. But, if value is immutable, modified value will be a
new object reference, and you must call setAttribute again. However, call
setAttribute every time if you want to support distributed sessions (where a
single app is distributed across multiple nodes in a cluster).
13
To Synchronize or Not to
Synchronize?Synchronize?
• The J2EE blueprints say not to bother
– There are no race conditions when multiple different
users access the page simultaneously
– On the face of it it seems practically impossible for the– On the face of it, it seems practically impossible for the
same user to access the session concurrently
• The rise of Ajax makes synchronizationj y
important
– With Ajax calls, it is actually quite likely that two
requests from the same user could arrive concurrentlyrequests from the same user could arrive concurrently
• Performance tip
– Don’t do “synchronized(this)”!Don t do synchronized(this) !
• Use the session or perhaps the value from the session as
the label of the synchronized block
14
What Changes if Server Uses
URL Rewriting?URL Rewriting?
• Session tracking code:
– No change
• Code that generates hypertext links back to
same site:same site:
– Pass URL through response.encodeURL.
• If server is using cookies, this returns URL unchangedIf server is using cookies, this returns URL unchanged
• If server is using URL rewriting, this appends the session
info to the URL
• E.g.:E.g.:
String url = "order-page.html";
url = response.encodeURL(url);
• Code that does sendRedirect to own site:• Code that does sendRedirect to own site:
– Pass URL through response.encodeRedirectURL
15
HttpSession Methods
• getAttribute
– Extracts a previously stored value from a session object.
Returns null if no value is associated with given name.
• setAttribute• setAttribute
– Associates a value with a name. Monitor changes: values
implement HttpSessionBindingListener.p p g
• removeAttribute
– Removes values associated with name.
• getAttributeNames
– Returns names of all attributes in the session.
tId• getId
– Returns the unique identifier.
16
HttpSession Methods
(Continued)(Continued)
• isNew
– Determines if session is new to client (not to page)
• getCreationTime
R i hi h i fi d– Returns time at which session was first created
• getLastAccessedTime
Returns time at which session was last sent from client– Returns time at which session was last sent from client
• getMaxInactiveInterval, setMaxInactiveInterval
– Gets or sets the amount of time session should go withoutGets or sets the amount of time session should go without
access before being invalidated
• invalidate
– Invalidates current session
17
© 2010 Marty Hall
Storing Simple Values
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.18
A Servlet that Shows Per-Client
Access CountsAccess Counts
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request,p ( p q q ,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request getSession();HttpSession session = request.getSession();
synchronized(sesssion) {
String heading;
Integer accessCount =
(Integer)session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome Newcomer";heading = Welcome, Newcomer ;
} else {
heading = "Welcome Back";
accessCount =
new Integer(accessCount.intValue() + 1);
}
session.setAttribute("accessCount", accessCount);
19
A Servlet that Shows Per-Client
Access Counts (Continued)Access Counts (Continued)
PrintWriter out = response.getWriter();
……
out.println
(docType +
"<HTML>n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<CENTER>n" +
"<H1>" + heading + "</H1>n" +<H1> + heading + </H1>n +
"<H2>Information on Your Session:</H2>n" +
"<TABLE BORDER=1>n" +
"<TR BGCOLOR="#FFAD00">n" +
" <TH>Info Type<TH>Valuen" +
…
" <TD>Number of Previous Accessesn" +
" <TD>" + C t + " " +" <TD>" + accessCount + "n" +
"</TABLE>n" +
"</CENTER></BODY></HTML>");
}20
A Servlet that Shows Per-Client
Access Counts: User 1Access Counts: User 1
21
A Servlet that Shows Per-Client
Access Counts: User 2Access Counts: User 2
22
© 2010 Marty Hall
Storing Lists of Values
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.23
Aside: Compilation Warnings re
Unchecked TypesUnchecked Types
• HttpSession does not use generics
– Since it was written pre-Java5. So, following is illegal:
HttpSession<ArrayList<String>> session =
request.getSession();
• Typecasting to a generic type results in a
compilation warning
Htt S i i t tS i ()HttpSession session = request.getSession();
List<String> listOfBooks =
(List<String>)session.getAttribute("book-list");
…
– Still compiles and runs, but warning is annoying
• You can suppress warningsYou can suppress warnings
– Put the following before line of code that does typecast:
@SuppressWarnings("unchecked")
24
Accumulating a List
of User Dataof User Data
public class ShowItems extends HttpServlet {
public void doPost(HttpServletRequest request,public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
synchronized(session) {
@SuppressWarnings("unchecked")
List<String> previousItems =
(List<String>)session getAttribute("previousItems");(List<String>)session.getAttribute( previousItems );
if (previousItems == null) {
previousItems = new ArrayList<String>();
session.setAttribute("previousItems", previousItems);
}
String newItem = request.getParameter("newItem");
if ((newItem != null) &&
(! It t i () l (""))) {(!newItem.trim().equals(""))) {
previousItems.add(newItem);
}
25
Accumulating a List
of User Data (Continued)of User Data (Continued)
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Items Purchased";
String docType =
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +
"Transitional//EN">n";
o t println(docT pe +out.println(docType +
"<HTML>n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1>" + title + "</H1>");<H1> + title + </H1> );
if (previousItems.size() == 0) {
out.println("<I>No items</I>");
} else {
out.println("<UL>");out.println( <UL> );
for(String item: previousItems) {
out.println(" <LI>" + item);
}
out.println("</UL>");p
}
out.println("</BODY></HTML>");
}
}}26
Accumulating a List
of User Data: Front Endof User Data: Front End
27
Accumulating a List
of User Data: Resultof User Data: Result
28
© 2010 Marty Hall
Advanced Features
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.29
Distributed and Persistent
SessionsSessions
• Some servers support distributed Web apps
L d b l i d t d diff t t t diff t– Load balancing used to send different requests to different
machines. Sessions should still work even if different hosts are hit.
• On some servers, you must call setAttribute to trigger replication
– This is a tradeoff: session duplication can be expensive but givesThis is a tradeoff: session duplication can be expensive, but gives
you better load balancing
• Some servers suport persistent sessions
Session data written to disk and reloaded when server is restarted– Session data written to disk and reloaded when server is restarted
(as long as browser stays open). Very important for web4!
• Tomcat 5 and 6 support this
• To support both session data should implement• To support both, session data should implement
the java.io.Serializable interface
– There are no methods in this interface; it is just a flag:
public class MySessionData implements Serializablepublic class MySessionData implements Serializable
...
}
– Builtin classes like String and ArrayList are already Serializable30
Letting Sessions Live Across
Browser RestartsBrowser Restarts
• Issue
– By default, Java sessions are based on cookies that live in
the browser’s memory, but go away when the browser is
closed. This is often, but not always, what you want.closed. This is often, but not always, what you want.
• Solution
– Explicitly send out the JSESSIONID cookie.p y
• Do this at the beginning of the user’s actions
• Call setMaxAge first
• Problem• Problem
– Using a cookie with a large maxAge makes no sense
unless the session timeout (inactiveInterval) is also large( ) g
– An overly large session timeout can waste server memory
31
An On-Line Bookstore
• Session tracking code stays the same as in
i l lsimple examples
• Shopping cart class is relatively complex
Id ifi i b i l ID– Identifies items by a unique catalog ID
– Does not repeat items in the cart
• Instead, each entry has a count associated with itInstead, each entry has a count associated with it
• If count reaches zero, item is deleted from cart
• Pages built automatically from objects that
h d i ti f b khave descriptions of books
32
An On-Line Bookstore
33
An On-Line Bookstore
34
© 2010 Marty Hall
Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.35
Summary
• Sessions do not travel across network
– Only unique identifier does
• Get the session
S i– request.getSession
• Extract data from session
session getAttribute– session.getAttribute
• Do typecast and check for null
• If you cast to a generic type, use @SuppressWarnings
• Put data in session
– session.setAttribute
C t l i i• Custom classes in sessions
– Should implement Serializable
36
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.37

Mais conteúdo relacionado

Mais procurados

Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Matt Raible
 
The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013Bastian Grimm
 
Changhao jiang facebook
Changhao jiang facebookChanghao jiang facebook
Changhao jiang facebookzipeng zhang
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessionsvantinhkhuc
 
Spring4 security
Spring4 securitySpring4 security
Spring4 securitySang Shin
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsrobertjd
 
Java Web Application Security - Utah JUG 2011
Java Web Application Security - Utah JUG 2011Java Web Application Security - Utah JUG 2011
Java Web Application Security - Utah JUG 2011Matt Raible
 
Octopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EEOctopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EERudy De Busscher
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICESSpring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICESMichael Plöd
 
RESTful Web Applications with Apache Sling
RESTful Web Applications with Apache SlingRESTful Web Applications with Apache Sling
RESTful Web Applications with Apache SlingBertrand Delacretaz
 
EWD 3 Training Course Part 26: Event-driven Indexing
EWD 3 Training Course Part 26: Event-driven IndexingEWD 3 Training Course Part 26: Event-driven Indexing
EWD 3 Training Course Part 26: Event-driven IndexingRob Tweed
 
In-browser storage and me
In-browser storage and meIn-browser storage and me
In-browser storage and meJason Casden
 
Super simple application security with Apache Shiro
Super simple application security with Apache ShiroSuper simple application security with Apache Shiro
Super simple application security with Apache ShiroMarakana Inc.
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationStormpath
 
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web frameworkAdam Kalsey
 

Mais procurados (20)

Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
 
The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013
 
Changhao jiang facebook
Changhao jiang facebookChanghao jiang facebook
Changhao jiang facebook
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Spring4 security
Spring4 securitySpring4 security
Spring4 security
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTs
 
Java Web Application Security - Utah JUG 2011
Java Web Application Security - Utah JUG 2011Java Web Application Security - Utah JUG 2011
Java Web Application Security - Utah JUG 2011
 
Octopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EEOctopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EE
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICESSpring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
 
RESTful Web Applications with Apache Sling
RESTful Web Applications with Apache SlingRESTful Web Applications with Apache Sling
RESTful Web Applications with Apache Sling
 
Web Apps
Web AppsWeb Apps
Web Apps
 
EWD 3 Training Course Part 26: Event-driven Indexing
EWD 3 Training Course Part 26: Event-driven IndexingEWD 3 Training Course Part 26: Event-driven Indexing
EWD 3 Training Course Part 26: Event-driven Indexing
 
In-browser storage and me
In-browser storage and meIn-browser storage and me
In-browser storage and me
 
Super simple application security with Apache Shiro
Super simple application security with Apache ShiroSuper simple application security with Apache Shiro
Super simple application security with Apache Shiro
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token Authentication
 
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web framework
 

Semelhante a Session Tracking and E-Commerce

02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptxssuser92282c
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=HibernateJay Shah
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overviewsohan1234
 
Java EE 8 Update
Java EE 8 UpdateJava EE 8 Update
Java EE 8 UpdateRyan Cuprak
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
07 cookies
07 cookies07 cookies
07 cookiessnopteck
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2
 

Semelhante a Session Tracking and E-Commerce (20)

02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=Hibernate
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Java EE 8 Update
Java EE 8 UpdateJava EE 8 Update
Java EE 8 Update
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
14 mvc
14 mvc14 mvc
14 mvc
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
07 cookies
07 cookies07 cookies
07 cookies
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
 
WSO2 AppDev platform
WSO2 AppDev platformWSO2 AppDev platform
WSO2 AppDev platform
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
Android networking-2
Android networking-2Android networking-2
Android networking-2
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
 

Mais de snopteck

13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
11 page-directive
11 page-directive11 page-directive
11 page-directivesnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
01 web-apps
01 web-apps01 web-apps
01 web-appssnopteck
 

Mais de snopteck (10)

10 jdbc
10 jdbc10 jdbc
10 jdbc
 
13 java beans
13 java beans13 java beans
13 java beans
 
11 page-directive
11 page-directive11 page-directive
11 page-directive
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 
03 form-data
03 form-data03 form-data
03 form-data
 
01 web-apps
01 web-apps01 web-apps
01 web-apps
 

Último

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Session Tracking and E-Commerce

  • 1. © 2010 Marty Hall S i T kiSession Tracking Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.3 © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Agenda • Implementing session tracking from scratch • Using basic session tracking • Understanding the session-tracking API Diff ti ti b t d b• Differentiating between server and browser sessions • Encoding URLs• Encoding URLs • Storing immutable objects vs. storing mutable objectsmutable objects • Tracking user access counts • Accumulating user purchasesg p • Implementing a shopping cart • Building an online store5 © 2010 Marty Hall Overview Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.6
  • 3. Session Tracking and E-Commerceand E-Commerce • Why session tracking? – When clients at on-line store add item to their shopping cart, how does server know what’s already in cart? – When clients decide to proceed to checkout how can– When clients decide to proceed to checkout, how can server determine which previously created cart is theirs? 7 Dilbert used with permission of United Syndicates Inc. Rolling Your Own Session Tracking: CookiesTracking: Cookies • Idea: associate cookie with data on server String sessionID = makeUniqueString(); HashMap sessionInfo = new HashMap(); HashMap globalTable = findTableStoringSessions(); globalTable.put(sessionID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sessionID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); Still to be done:• Still to be done: – Extracting cookie that stores session identifier – Setting appropriate expiration time for cookieSetting appropriate expiration time for cookie – Associating the hash tables with each request – Generating the unique session identifiers8
  • 4. Rolling Your Own Session Tracking: URL-RewritingTracking: URL-Rewriting • Idea – Client appends some extra data on the end of each URL that identifies the session – Server associates that identifier with data it has stored– Server associates that identifier with data it has stored about that session – E.g., http://host/path/file.html;jsessionid=1234 • Advantage – Works even if cookies are disabled or unsupported Di d t• Disadvantages – Must encode all URLs that refer to your own site All pages must be dynamically generated– All pages must be dynamically generated – Fails for bookmarks and links from other sites 9 Rolling Your Own Session Tracking: Hidden Form FieldsTracking: Hidden Form Fields • Idea: <INPUT TYPE="HIDDEN" NAME="session" VALUE="..."> • Advantage – Works even if cookies are disabled or unsupported • Disadvantages – Lots of tedious processing – All pages must be the result of form submissions 10
  • 5. © 2010 Marty Hall The Java Session-The Java Session- Tracking APIg Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.11 Session Tracking Basics • Access the session object – Call request.getSession to get HttpSession object • This is a hashtable associated with the user • Look up information associated with a• Look up information associated with a session. – Call getAttribute on the HttpSession object, cast theg p j , return value to the appropriate type, and check whether the result is null. Store information in a session• Store information in a session. – Use setAttribute with a key and a value. • Discard session data• Discard session data. – Call removeAttribute discards a specific value. – Call invalidate to discard an entire session.12
  • 6. Session Tracking Basics: Sample CodeSample Code HttpSession session = request.getSession(); synchronized(session) {synchronized(session) { SomeClass value = (SomeClass)session.getAttribute("someID"); if (value null) {if (value == null) { value = new SomeClass(...); session.setAttribute("someID", value); }} doSomethingWith(value); } • Do not need to call setAttribute again (after modifying value) if the modified value is the same object But if value is immutable modified value will be avalue is the same object. But, if value is immutable, modified value will be a new object reference, and you must call setAttribute again. However, call setAttribute every time if you want to support distributed sessions (where a single app is distributed across multiple nodes in a cluster). 13 To Synchronize or Not to Synchronize?Synchronize? • The J2EE blueprints say not to bother – There are no race conditions when multiple different users access the page simultaneously – On the face of it it seems practically impossible for the– On the face of it, it seems practically impossible for the same user to access the session concurrently • The rise of Ajax makes synchronizationj y important – With Ajax calls, it is actually quite likely that two requests from the same user could arrive concurrentlyrequests from the same user could arrive concurrently • Performance tip – Don’t do “synchronized(this)”!Don t do synchronized(this) ! • Use the session or perhaps the value from the session as the label of the synchronized block 14
  • 7. What Changes if Server Uses URL Rewriting?URL Rewriting? • Session tracking code: – No change • Code that generates hypertext links back to same site:same site: – Pass URL through response.encodeURL. • If server is using cookies, this returns URL unchangedIf server is using cookies, this returns URL unchanged • If server is using URL rewriting, this appends the session info to the URL • E.g.:E.g.: String url = "order-page.html"; url = response.encodeURL(url); • Code that does sendRedirect to own site:• Code that does sendRedirect to own site: – Pass URL through response.encodeRedirectURL 15 HttpSession Methods • getAttribute – Extracts a previously stored value from a session object. Returns null if no value is associated with given name. • setAttribute• setAttribute – Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener.p p g • removeAttribute – Removes values associated with name. • getAttributeNames – Returns names of all attributes in the session. tId• getId – Returns the unique identifier. 16
  • 8. HttpSession Methods (Continued)(Continued) • isNew – Determines if session is new to client (not to page) • getCreationTime R i hi h i fi d– Returns time at which session was first created • getLastAccessedTime Returns time at which session was last sent from client– Returns time at which session was last sent from client • getMaxInactiveInterval, setMaxInactiveInterval – Gets or sets the amount of time session should go withoutGets or sets the amount of time session should go without access before being invalidated • invalidate – Invalidates current session 17 © 2010 Marty Hall Storing Simple Values Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.18
  • 9. A Servlet that Shows Per-Client Access CountsAccess Counts public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request,p ( p q q , HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request getSession();HttpSession session = request.getSession(); synchronized(sesssion) { String heading; Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome Newcomer";heading = Welcome, Newcomer ; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } session.setAttribute("accessCount", accessCount); 19 A Servlet that Shows Per-Client Access Counts (Continued)Access Counts (Continued) PrintWriter out = response.getWriter(); …… out.println (docType + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<CENTER>n" + "<H1>" + heading + "</H1>n" +<H1> + heading + </H1>n + "<H2>Information on Your Session:</H2>n" + "<TABLE BORDER=1>n" + "<TR BGCOLOR="#FFAD00">n" + " <TH>Info Type<TH>Valuen" + … " <TD>Number of Previous Accessesn" + " <TD>" + C t + " " +" <TD>" + accessCount + "n" + "</TABLE>n" + "</CENTER></BODY></HTML>"); }20
  • 10. A Servlet that Shows Per-Client Access Counts: User 1Access Counts: User 1 21 A Servlet that Shows Per-Client Access Counts: User 2Access Counts: User 2 22
  • 11. © 2010 Marty Hall Storing Lists of Values Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.23 Aside: Compilation Warnings re Unchecked TypesUnchecked Types • HttpSession does not use generics – Since it was written pre-Java5. So, following is illegal: HttpSession<ArrayList<String>> session = request.getSession(); • Typecasting to a generic type results in a compilation warning Htt S i i t tS i ()HttpSession session = request.getSession(); List<String> listOfBooks = (List<String>)session.getAttribute("book-list"); … – Still compiles and runs, but warning is annoying • You can suppress warningsYou can suppress warnings – Put the following before line of code that does typecast: @SuppressWarnings("unchecked") 24
  • 12. Accumulating a List of User Dataof User Data public class ShowItems extends HttpServlet { public void doPost(HttpServletRequest request,public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); synchronized(session) { @SuppressWarnings("unchecked") List<String> previousItems = (List<String>)session getAttribute("previousItems");(List<String>)session.getAttribute( previousItems ); if (previousItems == null) { previousItems = new ArrayList<String>(); session.setAttribute("previousItems", previousItems); } String newItem = request.getParameter("newItem"); if ((newItem != null) && (! It t i () l (""))) {(!newItem.trim().equals(""))) { previousItems.add(newItem); } 25 Accumulating a List of User Data (Continued)of User Data (Continued) response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Items Purchased"; String docType = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " + "Transitional//EN">n"; o t println(docT pe +out.println(docType + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<H1>" + title + "</H1>");<H1> + title + </H1> ); if (previousItems.size() == 0) { out.println("<I>No items</I>"); } else { out.println("<UL>");out.println( <UL> ); for(String item: previousItems) { out.println(" <LI>" + item); } out.println("</UL>");p } out.println("</BODY></HTML>"); } }}26
  • 13. Accumulating a List of User Data: Front Endof User Data: Front End 27 Accumulating a List of User Data: Resultof User Data: Result 28
  • 14. © 2010 Marty Hall Advanced Features Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.29 Distributed and Persistent SessionsSessions • Some servers support distributed Web apps L d b l i d t d diff t t t diff t– Load balancing used to send different requests to different machines. Sessions should still work even if different hosts are hit. • On some servers, you must call setAttribute to trigger replication – This is a tradeoff: session duplication can be expensive but givesThis is a tradeoff: session duplication can be expensive, but gives you better load balancing • Some servers suport persistent sessions Session data written to disk and reloaded when server is restarted– Session data written to disk and reloaded when server is restarted (as long as browser stays open). Very important for web4! • Tomcat 5 and 6 support this • To support both session data should implement• To support both, session data should implement the java.io.Serializable interface – There are no methods in this interface; it is just a flag: public class MySessionData implements Serializablepublic class MySessionData implements Serializable ... } – Builtin classes like String and ArrayList are already Serializable30
  • 15. Letting Sessions Live Across Browser RestartsBrowser Restarts • Issue – By default, Java sessions are based on cookies that live in the browser’s memory, but go away when the browser is closed. This is often, but not always, what you want.closed. This is often, but not always, what you want. • Solution – Explicitly send out the JSESSIONID cookie.p y • Do this at the beginning of the user’s actions • Call setMaxAge first • Problem• Problem – Using a cookie with a large maxAge makes no sense unless the session timeout (inactiveInterval) is also large( ) g – An overly large session timeout can waste server memory 31 An On-Line Bookstore • Session tracking code stays the same as in i l lsimple examples • Shopping cart class is relatively complex Id ifi i b i l ID– Identifies items by a unique catalog ID – Does not repeat items in the cart • Instead, each entry has a count associated with itInstead, each entry has a count associated with it • If count reaches zero, item is deleted from cart • Pages built automatically from objects that h d i ti f b khave descriptions of books 32
  • 16. An On-Line Bookstore 33 An On-Line Bookstore 34
  • 17. © 2010 Marty Hall Wrap-up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.35 Summary • Sessions do not travel across network – Only unique identifier does • Get the session S i– request.getSession • Extract data from session session getAttribute– session.getAttribute • Do typecast and check for null • If you cast to a generic type, use @SuppressWarnings • Put data in session – session.setAttribute C t l i i• Custom classes in sessions – Should implement Serializable 36
  • 18. © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.37