26 Servlet Sessions

  • Upload
    rakesh

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

  • 7/25/2019 26 Servlet Sessions

    1/23

    Servlet Session Tracking

  • 7/25/2019 26 Servlet Sessions

    2/23

    2

    Persistent information

    A server site typically needs to maintain two kinds

    ofpersistent(remembered) information: Information about the session

    A sessionstarts when the user logs in or otherwise identifieshimselfherself! and continues until the user logs out or

    completes the transaction (for e"ample! makes a purchase)

    Information about the user #ser information must generally be maintained much longer

    than session information (for e"ample! remembering apurchase)

    This information must be stored on the server! for e"ample on

    a file or in a database

  • 7/25/2019 26 Servlet Sessions

    3/23

    3

    Server capabilities

    Servlets! like Applets! can be trustedor untrusted A servlet can use a uni$ue I% to store and retrieve information about a

    given session #ser information usually re$uires a login I% and a password Since servlets don&t $uit between re$uests! anyservlet can maintain

    information in its internal data structures! as long as the server keepsrunning

    A trustedservlet can read and write files on the server! hence can maintaininformation about sessions and users even when the server is stopped andrestarted

    An untrusted servlet will lose allinformation when the servlet or serverstops for any reason This is sometimes good enough for session information This is almost never good enough for user information

  • 7/25/2019 26 Servlet Sessions

    4/23

    4

    Session tracking

    'TTP is stateless: hen it gets a page re$uest! it has nomemoryof any previous re$uests from the same client This makes it difficult to hold a conversation*

    Typical e"ample: Putting things one at a time into a

    shopping cart! then checking out++each page re$uest mustsomehow be associated with previous re$uests

    The server must be able to keep track of multipleconversations with multiple users

    Session trackingis keeping track of what has gonebefore in this particular conversation Since 'TTP is stateless! it does not do this for you ,ou have to do it yourself! in your servlets

    ,ou can do this by maintaining a session I% for each user

  • 7/25/2019 26 Servlet Sessions

    5/23

    5

    Session tracking solutions

    'idden -form. fieldscan be used to store a uni$ue I%for the session

    /ookiesare small files that the servlet can store on theclient computer! and retrieve later

    #01 rewriting: ,ou can append a uni$ue I% after the#01 to identify the user

    2ava&s Session Tracking APIcan be used to do most ofthe work for you

  • 7/25/2019 26 Servlet Sessions

    6/23

    6

    'idden fields

    Advantages:

    All you need to know is how to read servlet parameters String sessionID = getParameter("sessionID") out.println("

  • 7/25/2019 26 Servlet Sessions

    7/237

    #sing hidden fields! I

    The very first re$uest that the user sends you will (typically)have nullfor the value of your hidden field hen your servlet sees the null! it can assign a uni$ue session I% and

    include it in a hidden field in the response

    3ach subse$uent re$uest will include this hidden field The servlet can keep session information in some data structure of its

    own! keyed by the session I%

    This is feasible because the servlet does not $uit between re$uests! so it

    can maintain information in its memory

    ,ou cannotassume the user will end the session the way youthink she should (say! by logging off) If the session data is sufficiently old!* you need to assume the user isn&t

    coming back! and discard the session data

  • 7/25/2019 26 Servlet Sessions

    8/238

    #sing hidden fields! II

    The session I% does not have to be the onlyhidden field ,ou can have other fields in addition to! or instead of! a

    session I% field This might be a good way to keep track of small amounts of

    simple information during a session 'idden fields are not particularly well suited to holding

    comple" or structured information

    In all cases! hidden fields are good onlyforstoring session information Information in servlet data structures will eventually be lost

    (when the servlet $uits) or get old and be discarded

  • 7/25/2019 26 Servlet Sessions

    9/239

    /ookies

    A cookieis a small bit of te"t sent to the client that can be readagain later 1imitations (for the protection of the client):

    6ot more than 789 per cookie (more than enough in general)

    6ot more than ; cookies per site

    6ot more than

  • 7/25/2019 26 Servlet Sessions

    10/2310

    #sing cookies

    import #ava$.servlet.http.% /onstructor: &oo'ie(String name String value)

    Assuming requestis an ttpServlet*e+uestand response

    is an ttpServlet*esponse!

    response.add&oo'ie(,oo'ie) &oo'ie- ,oo'ies = request.get&oo'ies()

    String name = ,oo'ies-i.get/ame()

    String value = ,oo'ies-i.get0alue()

    There are! of course! many more methods in the

    ttpServlet*e+uest! ttpServlet*esponse! and

    &oo'ieclasses in the #ava$.servlet.httppackage

  • 7/25/2019 26 Servlet Sessions

    11/2311

    Some more &oo'iemethods

    pu1li, void set&omment(String purpose) pu1li, String get&omment()

    pu1li, void set2a$3ge(int expiry)

    pu1li, int get2a$3ge() 4a" age in seconds after which cookie will e"pire If e$piryis negative! delete when browser e"its If e$piryis 5ero! delete cookie immediately

    setSe,ure(1oolean flag) pu1li, 1oolean getSe,ure() Indicates to the browser whether the cookie should only be sent using a

    secure protocol! such as 'TTPS or SS1

  • 7/25/2019 26 Servlet Sessions

    12/2312

    hat cookies are good for

    Advantages: 2ava&s Session Tracking API (to be discussed) makes cookies dead

    simple to use /ookies can easily contain more data than hidden fields %ata is stored on the client computer! not on yours

    This saves space on the server 4ay let you avoid keeping track of multiple(session) data structures

    %isadvantages: %ata is stored on the client computer! not on yours

    This means the data is neither safe nor secure Should not be used for user data++cookies may be discarded or the user

    may contact the server from another computer

    #sers can tell their browser to turn cookies off

    /ookies are good for keeping session data! not user data

  • 7/25/2019 26 Servlet Sessions

    13/2313

    2ava&s session tracking API! I

    'ere&s how yougeta session I% from the re$uest: ttpSession session = re+uest.getSession()

    'ere&s what this does for you: If

    the session includes a session I% cookie thenfind the session matching that session I%

    else(no session I% cookie or no matching session)

    create a new session

    This method does all the cookie work for you hether the session is a new one or a pre+e"isting one!

    you get an ttpSessionfor it

  • 7/25/2019 26 Servlet Sessions

    14/2314

    2ava&s session tracking API! II

    'ere&s how yousenda cookie in the response: ttpSession session = re+uest.getSession()

    hat this does for you: /reates a new ttpSessionob?ect! or retrieves a previous one /reates a uni$ue session I% 4akes a new cookie ob?ect Associates the cookie with the session I% Puts the cookie in the response (under the Set4&oo'ieheader)

    6otice that: This is e"actly the same call as in the previous slide The message is sent to the request! not the response

  • 7/25/2019 26 Servlet Sessions

    15/2315

    #sing an ttpSession

    session.set3ttri1ute(String name 51#e,t value) ,ou can save objectsin an ttpSession

    o1#e,t = session.get3ttri1ute(String name) ,ou can retrieve your saved ob?ects by name

    6numeration e = session.get3ttri1ute/ames() ,ou can find the names of all your ob?ects

    session.remove3ttri1ute(String name) ,ou can get rid of an ob?ect you no longer need

    1oolean session.is/e7() true if the session is newly created! rather than retrieved

    String id = session.getId() ,ou can get the session I% (if you&re debugging! or ?ust curious)

  • 7/25/2019 26 Servlet Sessions

    16/2316

    @uitting an ttpSession

    session.invalidate() @uits the session and unbinds any ob?ects in it

    millise,onds = session.get&reation8ime()

    (since midnight 2anuary ! BC; D4T)

    millise,onds = session.get9ast3,,essed8ime() (again! since BC;)

    session.set2a$Ina,tiveInterval(int se,onds)

    Sets the time until the session is automaticallyinvalidated

    int se,onds = session.get2a$Ina,tiveInterval()

    So the Session API does nearly everything you needE

  • 7/25/2019 26 Servlet Sessions

    17/2317

    #01 rewriting

    If the user has cookies turned off! you can use #01rewriting #01 rewriting is only used as a backup for cookies

    #01 rewriting adds the session I% to the end of every

    #01: URL #sessionid=:3;&D6?@A

    This is almostautomatic! but: /ookies must fail! and ,ou must e"plicitly encode* (add the e"tra information to)

    your #01s! for e"ample: out.println(",li,' me")

  • 7/25/2019 26 Servlet Sessions

    18/2318

    hat the /ontainer does

    If you are using the Session API! hen the /ontainer (Tomcat) starts a new session! it sends a

    cookie anddoes #01 rewriting

    If it gets a cookie back! it abandons #01 rewriting

    The /ontainer can&t ?ust send a cookie and see if it gets

    it back! because it can&t tell that what it gets back is

    from the same session

    A dumb* /ontainer may always send the cookie anddo #01 rewriting each time

  • 7/25/2019 26 Servlet Sessions

    19/2319

    4ore ttpServlet*e+uestmethods

    pu1li, ttpSession getSession() Dets the session ob?ect for this re$uest (or creates one if necessary)

    pu1li, 6numeration geteader/ames() Dets an 3numeration of all the field names in the 'TTP header

    pu1li, String geteader(String name) Diven the header name! return its value pu1li, int getInteader(String name)

    Diven the header name! return its value as an int 0eturns 4if no such header /ould throw a /um1erormat6$,eption

    pu1li, 6numeration geteaders(String name) Diven the header name! return an 6numerationof all its values

  • 7/25/2019 26 Servlet Sessions

    20/23

    20

    Summary: Session Tracking API

    The session tracking API is in #ava$.servlet.http.ttpSessionand is

    built on top of cookies

    To use the session tracking API: /reate a session:

    ttpSession session = request.getSession() 0eturns the session associated with this re$uest

    If there was no associated session! one is created

    Store information in the session and retrieve it as needed: session.set3ttri1ute(name value)

    51#e,t obj= get3ttri1ute(name) Session information is automatically maintained across re$uests

    To allow #01 rewriting! use response.en,odeB*9(yourURL)

  • 7/25/2019 26 Servlet Sessions

    21/23

    21

    =ther uses of cookies

    /ookies were devised for managing sessions! but youcan use them for other things

    ,ou can use cookies for storingsmallamounts of

    information on your client computers

    9y default! cookies are discarded when the browser

    $uits

    ,oo'ie.set2a$3ge(int seconds) If seconds is positive! cookie should persist for that long

    If seconds is negative! cookie is deleted when browser $uits

    If seconds is 5ero! cookie is deleted immediately

  • 7/25/2019 26 Servlet Sessions

    22/23

    22

    Summary

    A session is a continuous interaction with the user 'TTP is stateless! so the programmer must do something to

    remember session information

    There are multiple ways to remember session information

    The session ends when the user $uits the browser (or a session

    may be set to time out)

    Some information must be kept longer than ?ust within a

    session >or e"ample! if the user orders a product! that information must be

    kept in a database 1ong+term storage of information re$uires that the servlet have

    some additional privileges

  • 7/25/2019 26 Servlet Sessions

    23/23

    23

    The 3nd