Java EE Training

  • Upload
    899193

  • View
    234

  • Download
    0

Embed Size (px)

Citation preview

  • 8/9/2019 Java EE Training

    1/18

  • 8/9/2019 Java EE Training

    2/18

    Agenda

    Implementing session tracking from scratch

    Using basic session tracking

    Understanding the session-tracking API eren a ng e ween server an rowser

    sessions

    Storing immutable objects vs. storing

    Tracking user access counts

    Accumulatin user urchases 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 yourlocation.6

  • 8/9/2019 Java EE Training

    3/18

  • 8/9/2019 Java EE Training

    4/18

    Rolling Your Own Session

    IdeaClient appends some extra data on the end of each URL

    that identifies the session

    about that session

    E.g., http://host/path/file.html;jsessionid=1234

    AdvantageWorks even if cookies are disabled or unsupported

    sa van ages

    Must encode all URLs that refer to your own site

    Fails for bookmarks and links from other sites

    9

    Rolling Your Own Session

    Idea:

    Advantage

    Works even if cookies are disabled or unsupported

    DisadvantagesLots of tedious processing

    All pages must be the result of form submissions

    10

  • 8/9/2019 Java EE Training

    5/18

    2010 Marty Hall

    Tracking API

    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 yourlocation.11

    Session Tracking Basics

    Access the session objectCall request.getSession to get HttpSession object

    This is a hashtable associated with the user

    session.

    Call etAttribute on the Htt Session ob ect cast thereturn value to the appropriate type, and check whetherthe result is null.

    .Use setAttribute with a key and a value.

    .Call removeAttribute discards a specific value.

    Call invalidate to discard an entire session.12

  • 8/9/2019 Java EE Training

    6/18

    Session Tracking Basics:

    HttpSession session = request.getSession();

    SomeClass value =

    (SomeClass)session.getAttribute("someID");==

    value = new SomeClass(...);session.setAttribute("someID", value);

    doSomethingWith(value);

    }

    Do not need to call setAttribute again (after modifying value) if the modified. , ,

    new object reference, and you must call setAttribute again. However, callsetAttribute every time if you want to support distributed sessions (where asingle app is distributed across multiple nodes in a cluster).

    13

    To Synchronize or Not to

    The J2EE blueprints say not to botherThere are no race conditions when multiple different

    users access the page simultaneously

    ,same user to access the session concurrently

    The rise of Ajax makes synchronizationimportantWith Ajax calls, it is actually quite likely that two

    Performance tip

    Use the session or perhaps the value from the session asthe label of the synchronized block

    14

  • 8/9/2019 Java EE Training

    7/18

    What Changes if Server Uses

    Session tracking code:No change

    Code that generates hypertext links back to

    Pass URL through response.encodeURL. If server is usin cookies this returns URL unchan ed

    If server is using URL rewriting, this appends the sessioninfo to the URL

    . .String url = "order-page.html";url = response.encodeURL(url);

    Pass URL through response.encodeRedirectURL

    15

    HttpSession Methods

    getAttributeExtracts a previously stored value from a session object.

    Returns null if no value is associated with given name.

    Associates a value with a name. Monitor changes: values

    implement HttpSessionBindingListener. removeAttribute

    Removes values associated with name.

    getAttributeNamesReturns names of all attributes in the session.

    geReturns the unique identifier.

    16

  • 8/9/2019 Java EE Training

    8/18

    HttpSession Methods

    isNewDetermines if session is new to client(not to page)

    getCreationTime eturns t me at w c sess on was rst create

    getLastAccessedTime

    getMaxInactiveInterval, setMaxInactiveIntervalGets or sets the amount of time session should o 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 yourlocation.18

  • 8/9/2019 Java EE Training

    9/18

    A Servlet that Shows Per-Client

    public class ShowSession extends HttpServlet {public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {response.setContentType("text/html");= .

    synchronized(sesssion) {String heading;Integer accessCount =(Integer)session.getAttribute("accessCount");

    if (accessCount == null) {accessCount = new Integer(0);

    " ",} else {heading = "Welcome Back";accessCount =

    new Integer(accessCount.intValue() + 1);}session.setAttribute("accessCount", accessCount);

    19

    A Servlet that Shows Per-Client

    PrintWriter out = response.getWriter();out.println(docType +"\n" +"" + title + "\n" +"\n" +"\n" +" " " ""Information on Your Session:\n" +"\n" +"\n" +" Info TypeValue\n" +" Number of Previous Accesses\n" +" " + accessCount + " n" +"\n" +"");

    20

  • 8/9/2019 Java EE Training

    10/18

    A Servlet that Shows Per-Client

    21

    A Servlet that Shows Per-Client

    22

  • 8/9/2019 Java EE Training

    11/18

    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 yourlocation.23

    Aside: Compilation Warnings re

    HttpSession does not use genericsSince it was written pre-Java5. So, following is illegal:

    HttpSession session =request.getSession();

    Typecasting to a generic type results in acompilation warning

    p ess on sess on = reques .ge ess on ;

    List listOfBooks =

    (List)session.getAttribute("book-list");

    Still compiles and runs, but warning is annoying

    You can su ress warnin sPut the following before line of code that does typecast:

    @SuppressWarnings("unchecked")24

  • 8/9/2019 Java EE Training

    12/18

    Accumulating a List

    public class ShowItems extends HttpServlet {

    ublic void doPost Htt ServletRe uest re uest

    HttpServletResponse response)

    throws ServletException, IOException {HttpSession session = request.getSession();

    synchronized(session) {

    @SuppressWarnings("unchecked")

    List previousItems =

    " ".

    if (previousItems == null) {

    previousItems = new ArrayList();

    session.setAttribute("previousItems", previousItems);

    }

    String newItem = request.getParameter("newItem");

    if ((newItem != null) &&newI em. r m .equa s ""

    previousItems.add(newItem);

    }25

    Accumulating a List

    response.setContentType("text/html");PrintWriter out = response.getWriter();String title = "Items Purchased";String docType ="\n";

    ou .pr n n oc ype"\n" +"" + title + "\n" +"\n" +" " " "

    if (previousItems.size() == 0) {out.println("No items");

    } else {out. rintln ""for(String item: previousItems) {out.println(" " + item);

    }out.println("");

    }out.println("");

    }}}26

  • 8/9/2019 Java EE Training

    13/18

    Accumulating a List

    27

    Accumulating a List

    28

  • 8/9/2019 Java EE Training

    14/18

    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 yourlocation.29

    Distributed and Persistent

    Some servers support distributed Web apps oa a anc ng use o sen eren reques s o eren

    machines. Sessions should still work even if different hosts are hit. On some servers, you must call setAttribute to trigger replication

    ,you better load balancing

    Some servers suport persistent sessions

    (as long as browser stays open). Very important for web4!

    Tomcat 5 and 6 support this

    ,the java.io.Serializable interface There are no methods in this interface; it is just a flag:

    pu c c ass y ess on a a mp emen s er a za e...

    }

    Builtin classes like String and ArrayList are already Serializable30

  • 8/9/2019 Java EE Training

    15/18

    Letting Sessions Live Across

    IssueBy default, Java sessions are based on cookies that live in

    the browsers memory, but go away when the browser isclosed. This is often but not alwa s what ou want.

    SolutionExplicitly send out the JSESSIONID cookie.

    Do this at the beginning of the users actions

    Call setMaxAge first

    Using a cookie with a large maxAge makes no senseunless the session timeout (inactiveInterval) is also large

    An overly large session timeout can waste server memory

    31

    An On-Line Bookstore

    Session tracking code stays the same as insimple examples

    Shopping cart class is relatively complex ent es tems y a un que cata og

    Does not repeat items in the cart

    Instead each entr has a count associated with it If count reaches zero, item is deleted from cart

    Pages built automatically from objects thatave escr p ons o oo s

    32

  • 8/9/2019 Java EE Training

    16/18

    An On-Line Bookstore

    33

    An On-Line Bookstore

    34

  • 8/9/2019 Java EE Training

    17/18

    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 yourlocation.35

    Summary

    Sessions do not travel across networkOnly unique identifier does

    Get the session request.get ess on

    Extract data from session .

    Do typecast and check for null

    If you cast to a generic type, use @SuppressWarnings

    Put data in session session.setAttribute

    us om c asses n sess onsShould implement Serializable

    36

  • 8/9/2019 Java EE Training

    18/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 yourlocation.37