Rk Jsp Session Cookies

download Rk Jsp Session Cookies

of 39

Transcript of Rk Jsp Session Cookies

  • 8/7/2019 Rk Jsp Session Cookies

    1/39

    Tracking Users

    withSessions and Cookies

  • 8/7/2019 Rk Jsp Session Cookies

    2/39

    Tracking Users with Sessions andCookies

    There are several ways of tracking users, including the following:There are several ways of tracking users, including the following: Hidden textHidden textUsing hidden controls in a Web page is the easiest way ofUsing hidden controls in a Web page is the easiest way of

    associating some information with the user that's not directly accessible toassociating some information with the user that's not directly accessible tohim. However, the hidden text can be seen if the user looks at the HTMLhim. However, the hidden text can be seen if the user looks at the HTMLfor the Web page directly.for the Web page directly.

    CookiesCookiesThis is probably the most common way of tracking users on theThis is probably the most common way of tracking users on theInternet. You can store information in a user's computer using cookies, andInternet. You can store information in a user's computer using cookies, and

    retrieve it when you need it. You can also specify how long the cookieretrieve it when you need it. You can also specify how long the cookieshould exist before being deleted by the browser.should exist before being deleted by the browser. SessionsSessionsSessions are something the server offers us to support userSessions are something the server offers us to support user

    tracking, and they're great, although they can take up a lot of resources ontracking, and they're great, although they can take up a lot of resources onthe server. Sessions let you preserve data between accesses to a Web pagethe server. Sessions let you preserve data between accesses to a Web pageby the same user.by the same user.

    ApplicationsApplicationsApplications are much like sessions, as you'll see, but they'reApplications are much like sessions, as you'll see, but they're

    more generalmore generalyou can share data between all the JSP pages in a site usingyou can share data between all the JSP pages in a site usingapplications. In other words, unlike sessions, applications can be used toapplications. In other words, unlike sessions, applications can be used totrack multiple users at the same time.track multiple users at the same time.

    Sessions, applications, and JavaBeansSessions, applications, and JavaBeansYou can also set JavaBeans soYou can also set JavaBeans sothey'll be included in a session or application. Normally, the data in athey'll be included in a session or application. Normally, the data in aJavaBean is reset each time the user accesses a page and creates an objectJavaBean is reset each time the user accesses a page and creates an objectfrom that bean, but you can include the bean in a session or application sofrom that bean, but you can include the bean in a session or application soits data is preserved between accesses by the same user.its data is preserved between accesses by the same user.

  • 8/7/2019 Rk Jsp Session Cookies

    3/39

    Hidden Controls

  • 8/7/2019 Rk Jsp Session Cookies

    4/39

    Using Hidden Controls

    Using HTML hidden controls is an easy way toUsing HTML hidden controls is an easy way tostore data in a Web page.store data in a Web page.

    For example, in this JSP page, the code willFor example, in this JSP page, the code will

    let the user set the text to store in a hiddenlet the user set the text to store in a hiddencontrol in a text field:control in a text field:

  • 8/7/2019 Rk Jsp Session Cookies

    5/39

    Example Setting/Reading Hidden Text

    Reading Hidden ControlsReading Hidden Controls

    Reading Hidden ControlsReading Hidden Controls

    VALUE="">

  • 8/7/2019 Rk Jsp Session Cookies

    6/39

    Cookies

  • 8/7/2019 Rk Jsp Session Cookies

    7/39

    What are Cookies ?

    Cookies are short pieces of data sent by web serversCookies are short pieces of data sent by web serversto the client browser.to the client browser.

    The cookies are saved to clients hard disk in theThe cookies are saved to clients hard disk in theform of small text file.form of small text file.

    Cookies helps the web servers to identify web users,Cookies helps the web servers to identify web users,by this way server tracks the user.by this way server tracks the user.

    Cookies pay very important role in the sessionCookies pay very important role in the session

    tracking.tracking.

  • 8/7/2019 Rk Jsp Session Cookies

    8/39

    Cookie Class

    In JSP cookie are the object of the classIn JSP cookie are the object of the classjavax.servlet.http.Cookiejavax.servlet.http.Cookie..

    This class is used to creates a cookie, a small amount ofThis class is used to creates a cookie, a small amount ofinformation sent by a servlet to a Web browser, saved by theinformation sent by a servlet to a Web browser, saved by thebrowser, and later sent back to the server.browser, and later sent back to the server.

    A cookie's value can uniquely identify a client, so cookies areA cookie's value can uniquely identify a client, so cookies arecommonly used for session management.commonly used for session management.

    A cookie has a name, a single value, and optional attributesA cookie has a name, a single value, and optional attributessuch as a comment, path and domain qualifiers, a maximumsuch as a comment, path and domain qualifiers, a maximumage, and a version number.age, and a version number.

    The getCookies() method of the request object returns anThe getCookies() method of the request object returns anarray of Cookie objects.array of Cookie objects.

    Cookies can be constructed using the following code:Cookies can be constructed using the following code:

    Cookie(java.lang.String name,java.lang.String value)Cookie(java.lang.String name,java.lang.String value)

  • 8/7/2019 Rk Jsp Session Cookies

    9/39

    Cookie Methods

    Method Description

    getComment()

    Returns the comment describing the purpose of this cookie, or null if no such

    comment has been defined.

    getMaxAge() Returns the maximum specified age of the cookie.

    getName() Returns the name of the cookie.

    getPath() Returns the prefix of all URLs for which this cookie is targeted.

    getValue() Returns the value of the cookie.

    setComment(String)

    If a web browser presents this cookie to a user, the cookie's purpose will bedescribed using this comment.

    setMaxAge(int)

    Sets the maximum age of the cookie. The cookie will expire after that many

    seconds have passed. Negative values indicate the default behavior: the

    cookie is not stored persistently, and will be deleted when the user web

    browser exits. A zero value causes the cookie to be deleted

    setPath(String) This cookie should be presented only with requests beginning with this URL.

    setValue(String)

    Sets the value of the cookie. Values with various special characters (white

    space, brackets and parentheses, the equals sign, comma, double quote,

    slashes, question marks, the "at" sign, colon, and semicolon) should be

    avoided. Empty values may not behave the same way on all browsers.

  • 8/7/2019 Rk Jsp Session Cookies

    10/39

    Creating a Cookie

    Here, the code will create a cookie and place someHere, the code will create a cookie and place sometext in it, and another page will read the cookie andtext in it, and another page will read the cookie anddisplay that text.display that text.

    To create the cookie, you use the Cookie class'sTo create the cookie, you use the Cookie class's

    constructor, passing it the name of the cookieconstructor, passing it the name of the cookie(which will be message here) and the text in the(which will be message here) and the text in thecookie (which will just be "Hello!" in this case).cookie (which will just be "Hello!" in this case).

    You can also set the length of time the cookie willYou can also set the length of time the cookie willexist on the user's computer with theexist on the user's computer with the setMaxAgesetMaxAgemethod, which you pass a value in seconds tomethod, which you pass a value in seconds tototomake the cookie last for a day, you can pass a valuemake the cookie last for a day, you can pass a valueof 24 * 60 * 60 this way:of 24 * 60 * 60 this way:

  • 8/7/2019 Rk Jsp Session Cookies

    11/39

    Setting a Cookie Example1

    Setting a CookieSetting a Cookie

    Setting a CookieSetting a Cookie

    Read the cookieRead the cookie

  • 8/7/2019 Rk Jsp Session Cookies

    12/39

    cookieform.jsp

    This example uses a form to accept the Value and sets it as a cookie value inThis example uses a form to accept the Value and sets it as a cookie value inthe cookie.the cookie.

    Cookie Input FormCookie Input Form

    Enter Your Name:

  • 8/7/2019 Rk Jsp Session Cookies

    13/39

    setcookie.jsp

    Cookie Saved Cookie Saved

    Next Page to view the cookie

    Next Page to view the cookie

    value

    value

  • 8/7/2019 Rk Jsp Session Cookies

    14/39

    showCookieValue.jsp

    Show Saved Cookie

    No Cookie found with the name No Cookie found with the name

    Welcome: .

    Welcome: .

  • 8/7/2019 Rk Jsp Session Cookies

    15/39

    Reading a Cookie

    To read a cookie in the user's computer, you use theTo read a cookie in the user's computer, you use therequest object's getCookiesrequest object's getCookies method.method.

    This method returns an array of Cookie objects (or null ifThis method returns an array of Cookie objects (or null ifthere are no cookies) So how do you read the cookiethere are no cookies) So how do you read the cookienamed message?named message?

    Are you passed all the cookies on the computer?Are you passed all the cookies on the computer? No, you're only passed the cookies that came from theNo, you're only passed the cookies that came from the

    same domain as the page you're using the getCookiessame domain as the page you're using the getCookiesmethod in.method in.

    In the NextExampleIn the NextExample Inside the body of the loop, you can get the name ofInside the body of the loop, you can get the name of

    each cookie with theeach cookie with the Cookie class's getName methodCookie class's getName method,,and itsand its value with the getValue methodvalue with the getValue method..

    If the code finds the message cookie, it displays thatIf the code finds the message cookie, it displays thatcookie's value.cookie's value.

  • 8/7/2019 Rk Jsp Session Cookies

    16/39

    Reading a Cookie - Example

    Reading a CookieReading a Cookie

    Reading a CookieReading a Cookie

  • 8/7/2019 Rk Jsp Session Cookies

    17/39

    Setting and Reading a Cookiein the Same Page

  • 8/7/2019 Rk Jsp Session Cookies

    18/39

    Setting and Reading a Cookie in the Same Page - Example

    Setting and Reading CookiesSetting and Reading Cookies Setting and Reading CookiesSetting and Reading Cookies

    This page will set its background color using a cookie.This page will set its background color using a cookie.

    When you load this page the firsttime, it sets the color cookie, andthe page background will bewhite. When you load the pagefrom then on, until the cookieexpires, the page reads thatcookie and uses it to turn thepage background cyan

  • 8/7/2019 Rk Jsp Session Cookies

    19/39

    Setting/Reading Cookie Properties

  • 8/7/2019 Rk Jsp Session Cookies

    20/39

    Setting/Reading Cookie Properties contd

    // Checking properties of the received cookies// Checking properties of the received cookiesout.println("Properties of the received cookies:
    ");out.println("Properties of the received cookies:
    ");Cookie[] cookies = request.getCookies();Cookie[] cookies = request.getCookies();int n = 0;int n = 0;if (cookies!=null) {if (cookies!=null) {

    n = cookies.length ;n = cookies.length ;

    for (int i=0; i%>

  • 8/7/2019 Rk Jsp Session Cookies

    21/39

    Output

  • 8/7/2019 Rk Jsp Session Cookies

    22/39

    Sessions

  • 8/7/2019 Rk Jsp Session Cookies

    23/39

    Creating a Session

    Using sessions such as this is great for storing and recoveringUsing sessions such as this is great for storing and recoveringdatadatait provides you with an environment much like ait provides you with an environment much like astandard program, where you interact with the user withoutstandard program, where you interact with the user withouthaving to worry about having your data reset.having to worry about having your data reset.

    This next example will show how to store the number ofThis next example will show how to store the number oftimes the user has accessed the page in the current session,times the user has accessed the page in the current session,as well as how to get the session ID, when the session wasas well as how to get the session ID, when the session wascreated, and the last time the page was accessed in thecreated, and the last time the page was accessed in thecurrent session.current session.

    This example starts with the page directivThis example starts with the page directiv

    With the directive's session attribute set to true.With the directive's session attribute set to true.

  • 8/7/2019 Rk Jsp Session Cookies

    24/39

    javax.servlet.http.HttpSession Methods

    Method Does This

    void addCookie(Cookie cookie) Adds the specif ied cookie to the response object.

    java.lang.Object getAttribute(java.lang.String name)

    Returns the object of the given name in this session.

    java.util.Enumeration getAttributeNames() Returns a Java Enumeration of String objects containing the names of all the objects in this session.

    long getCreationTime() Returns the time when this session was created (measured in milliseconds since midnight January 1, 1970GMT).

    java.lang.String getId() Returns a string containing the identifier for this session.

    long getLastAccessedTime() Returns the last time the client sent a request in with this session, as the number of milliseconds since

    midnight January 1, 1970 GMT.

    int getMaxInactiveInterval() Returns the maximum time, in seconds, which the server will keep this session open between clientaccesses.

    ServletContext getServletContext() Returns the ServletContext to which this session belongs.

    HttpSessionContext getSessionContext() As of servlet specification version 2.1, this method is deprecated.

    java.lang.Object getValue(java.lang.Stringname)

    Deprecated. As of servlet specification version 2.2, this method is replaced by getAttribute(java.lang.String).

    java.lang.String[] getValueNames() Deprecated. As of servlet specification version 2.2, this method is replaced by getAttributeNames().

    void invalidate() Invalidates this session.

    boolean isNew() Returns true if the client does not yet know about the session.

    void putValue(java.lang.String name,java.lang.Object value)

    Deprecated. As of servlet specification version 2.2, this method is replaced by setAttribute(java.lang.String,java.lang.Object).

    void removeAttribute(java.lang.Stringname)

    Removes the object with the specified name from this session.

    void removeValue(java.lang.String name) As of servlet specification version 2.2, this method is replaced by removeAttribute(java.lang.String).

    void setAttribute(java.lang.String name,java.lang.Object value) Connects an object to this session, using the given name.

  • 8/7/2019 Rk Jsp Session Cookies

    25/39

    Creating a Session - Example

    Using Sessions to Track UsersUsing Sessions to Track Users

    Using Sessions to Track UsersUsing Sessions to Track Users

    Session ID: Session ID:

    Session creation time: Session creation time:

    Last accessed time: Last accessed time:

    Number of times you've been here: Number of times you've been here:

  • 8/7/2019 Rk Jsp Session Cookies

    26/39

    Session Example

    out.println( "" ); %>

  • 8/7/2019 Rk Jsp Session Cookies

    27/39

    Setting Session Timeouts

    You can use methods of the session object to set theYou can use methods of the session object to set themaximum time between page accesses before the servermaximum time between page accesses before the serverends the session:ends the session:

    getMaxInactiveInterval()getMaxInactiveInterval()Returns the maximum timeReturns the maximum timeinterval, in seconds, for which the server will keep thisinterval, in seconds, for which the server will keep thissession open between accesses.session open between accesses.

    setMaxInactiveInterval(intsetMaxInactiveInterval(int intervalinterval))Specifies the time, inSpecifies the time, inseconds, between user requests before the servletseconds, between user requests before the servletcontainer will invalidate this session.container will invalidate this session.

    If you set the lifetime of a session toIf you set the lifetime of a session to --1, the session will never1, the session will neverexpire.expire.

    The default timeout between user accesses for sessions inThe default timeout between user accesses for sessions inTomcat is 30 minutes.Tomcat is 30 minutes.

    You can change this in Tomcat's web.xml file (stored asYou can change this in Tomcat's web.xml file (stored asjakartajakarta--tomcattomcat--4.0.34.0.3\\confconf\\web.xml). All you have to do isweb.xml). All you have to do ischange the time stored in the element:

  • 8/7/2019 Rk Jsp Session Cookies

    28/39

    Setting Session Timeouts - Example

    >

    >>

  • 8/7/2019 Rk Jsp Session Cookies

    29/39

    Application Object

  • 8/7/2019 Rk Jsp Session Cookies

    30/39

    Using Applications

    A session enables you to track one user at a timeA session enables you to track one user at a timeananapplication enables you to track all JSPs in the same site, noapplication enables you to track all JSPs in the same site, nomatter how many users are using them.matter how many users are using them.

    To access the current application, you can use the builtTo access the current application, you can use the built--ininJSP application object.JSP application object.

    Like the session object, the application object is based on theLike the session object, the application object is based on thejavax.servlet.http.HttpSessionjavax.servlet.http.HttpSession interface.interface.

    In the previous example, you saw how to create a sessionIn the previous example, you saw how to create a sessionattribute named counter, which stores the number of timesattribute named counter, which stores the number of timesthe user has visited the page in the current session.the user has visited the page in the current session.

    In the same way, you can create an application attributeIn the same way, you can create an application attributenamednamed applicationCounterapplicationCounter that holds the total number ofthat holds the total number oftimes anyone in the same application has viewed a JSP page.times anyone in the same application has viewed a JSP page.

  • 8/7/2019 Rk Jsp Session Cookies

    31/39

    Using Applications - Example Using the Application Object Using the Application Object

    Using the Application ObjectUsing the Application Object

    You have visited this page times.
    You have visited this page times.

    This page has been visited by all users times.This page has been visited by all users times.

  • 8/7/2019 Rk Jsp Session Cookies

    32/39

    Sessions, Applications, and

    JavaBeans

  • 8/7/2019 Rk Jsp Session Cookies

    33/39

    Using Sessions, Applications, and JavaBeans

    It turns out that you can instruct Tomcat to save JavaBeansIt turns out that you can instruct Tomcat to save JavaBeansin a session object as well as in attributes.in a session object as well as in attributes.

    In fact, you can store JavaBeans in applications as well.In fact, you can store JavaBeans in applications as well.

    You do this with the element's scopeYou do this with the element's scopeattribute, which you can set to one of these values:attribute, which you can set to one of these values:

    scope="page |request|session|application"scope="page |request|session|application".. The termThe term scopescope indicates where a data item is "visible"indicates where a data item is "visible"

    (meaning it may be referred to by name) in your code.(meaning it may be referred to by name) in your code.

    The default scope for a bean is page scope, which means theThe default scope for a bean is page scope, which means thebean exists only for the page scope.bean exists only for the page scope.

    However, if you set the scope of a bean to session, it isHowever, if you set the scope of a bean to session, it isstored with the rest of the session's data.stored with the rest of the session's data.

  • 8/7/2019 Rk Jsp Session Cookies

    34/39

    Bean

    A Bean That Maintains a Usage Counter (ch07_07.jsp)A Bean That Maintains a Usage Counter (ch07_07.jsp)

    package beans;package beans;public class ch07_07public class ch07_07{{private int counter = 0;private int counter = 0;

    public void setCounter(int value)public void setCounter(int value){{this.counter = value;this.counter = value;

    }}

    public int getCounter()public int getCounter()

    {{ return this.counter;return this.counter;}}public ch07_07()public ch07_07(){{}}

    }}

  • 8/7/2019 Rk Jsp Session Cookies

    35/39

    Using Page Scope for Beans (ch07_08.jsp)

    Using Beans and Page ScopeUsing Beans and Page Scope

    Using Beans and Page ScopeUsing Beans and Page Scope

    The counter value is:

  • 8/7/2019 Rk Jsp Session Cookies

    36/39

    Using Session Scope for Beans (ch07_09.jsp)

    Using Beans and Session ScopeUsing Beans and Session Scope

    Using Beans and Session ScopeUsing Beans and Session Scope

    The counter value is:

  • 8/7/2019 Rk Jsp Session Cookies

    37/39

    Q&A

    Q. Are there any drawbacks to using sessions?Q. Are there any drawbacks to using sessions?

    Ans. Yes, they put a considerable strain on the resources of theAns. Yes, they put a considerable strain on the resources of theserver if there are many sessions running at the same time.server if there are many sessions running at the same time.They can also be broken unexpectedly if the user'sThey can also be broken unexpectedly if the user'sconnection fails. All in all, in professional JSP applications,connection fails. All in all, in professional JSP applications,

    you must be prepared for cases when using a session withyou must be prepared for cases when using a session withthe user doesn't work.the user doesn't work.

    Q. Can I store other data in cookies besides the cookie'sQ. Can I store other data in cookies besides the cookie'sname, maximum age, and value?name, maximum age, and value?

    ANS. Yes, you can also use the Cookie object's setCommentANS. Yes, you can also use the Cookie object's setComment

    and getComment methods to store a commentand getComment methods to store a commenta Stringa Stringobjectobjectin the cookie. This comment can explain thein the cookie. This comment can explain thepurpose of the cookie, for example.purpose of the cookie, for example.

  • 8/7/2019 Rk Jsp Session Cookies

    38/39

  • 8/7/2019 Rk Jsp Session Cookies

    39/39