Cookies and Sessions?

I am trying to set the maxAge in cookies using this code
Cookie cookie = new Cookie("cookie1","test");
cookie.setMaxAge(360);
cookie.setComment("test comments");
response.addCookie(cookie);I am retrieving the cookie using this code:
Cookie[] cookieArray = request.getCookies();
if( cookieArray != null) {
    for( int i = cookieArray.length-1; i >= 0; i-- ) {
       Cookie cookie = cookieArray;
out.println("Cookie name is " + cookie.getName() + "<br>");
out.println("Cookie value is " + cookie.getValue() + "<br>");
out.println("Cookie age is " + cookie.getMaxAge() + "<br>");
out.println("cookie comment is " + cookie.getComment() + "<br>");
The name and value are returned, but the maxAge=-1 and the comment is null. Any idea why? I also tried setting the maxAge to 0 after the cookie has been set the first time. The cookie still persists. Does the cookie persist forever if the maxAge is not set?
Also, I was wondering if you can use httpSession after the browser closes. If the user closes the browser, is it possible to get the session back when they open it again by setting the maxInterval?

Nothing reading the API wouldn't cure...
"This class [Cookie] supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability." ... "Comments are not supported by Netscape Version 0 cookies."
This partly explains the comment problem (see setVersion(int)), except that it doesn't necessarily mean the browser will send the comment back. So you can try setting it, but I would never expect it to be there when read back.
"public void setMaxAge(int expiry)
A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age.
A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted."
The default max age is -1 (or at least some negative value). As for get, again, I wouldn't assume that the browser will send this information back.
Generally, if the cookie name/value is present, it hasn't expired, so great. If you want to reset it even if it still exists, or wait til it no longer exists, that's up to you. I wouldn't rely on other information.
In particular, I don't think getting back the max age will help with anything. There is no way to tell from it anything useful from it. It's not like you could figure out how long it's been since it was set. It wouldn't return any value such as time remaining. If you wanted to do something like that, you could set another cookie with a timestamp as the value and read that later.

Similar Messages

  • Differences between cookies and sessions

    Hi there,
    I want to learn the differences between sessions and cookies in PHP.Please help me.
    Please let me know if there any video demonstrations that explain sessions and cookies.
    Thanks in advance.

    Cookies and server side sessions are related in that they are both ways to persist data. This is required because of the fact that http is a stateless protocol, meaning that each request and response are independent transactions. Cookies are stored on the client. You might use them to store the contents of a shopping cart, or a user login id for a particular site. Or you could store a setting so that the user is automatically logged in, similar to what occurs here in the adobe site / forums. You can set various options for when cookies expire. Cookies that persist when the browser is closed are store in files, otherwise they could be store in memory only. Cookies can be created using either client or server side code.
    Server side sessions are created on the server with a server side scripting language. A session id is generated and stored as a token on the client (in an in memory cookie) so that the server can track requests from the same originating client. Session variables are ways to store data related to the session on the server. Sessions use server resources which is why you should only use them when necessary and destroy them when done. When the session is destroyed, the session variables are gone so if you want to keep them for later you can store them in a database or store them in a cookie.
    HTTP cookie - Wikipedia, the free encyclopedia
    Hope that helps

  • 3 question about cookie and session please.

    1. I know that session automatic use in JSP by default and save session id in cookie. I have code that show all cookie on my computer
    <%
         Cookie [ ] listcookie = request.getCookies();
         Cookie mycookie = null;
         for(int i=0; i<listcookie.length; i++)
              mycookie = listcookie;
              out.println("<tr><td> " + mycookie.getName() + "</td>");
              out.println("<td> " + mycookie.getValue() + "</td></tr>");
    %>
    When I first run this code it now show cookie. But when I click refresh it show session cookie. Why it not show session cookie at first time?
    2. I use tomcat on window. Is session on server is save as file. Which directory it save?
    3. I use method getCreationTime() to check first create session time and method session.getLastAccessedTime() to check last access session time. I have to file
    showsession1.jsp
    first time create is <%=session.getCreationTime()%>  <br>
    last time access is <%=session.getLastAccessedTime()%> <br>
    <a href="showsession2.jsp"> showsession2.jsp</a>showsession2.jsp
    first time create is <%=session.getCreationTime()%>  <br>
    last time access is <%=session.getLastAccessedTime()%> <br>When I open browser and run showsession1.jsp first time create and last time access is equal when I click link to showsession2.jsp it also equal. Why it still equal because it is second time that I access JSP file? It change when I refresh file showsession2.jsp

    1. When I first run this code it now show cookie. But
    when I click refresh it show session cookie. Why it
    not show session cookie at first time?
    When you first request the JSP, the session cookie does not exist on your PC and so your browser cannot supply it which means that the JSP cannot display it. The session cookie is created when the JSP returns the response to the first request. The browser can then send the cookie on subsequent requests.
    2. I use tomcat on window. Is session on server is
    save as file. Which directory it save?How the server saves the session info is server dependent and it's unlikely you will be able to view it.
    3. I use method getCreationTime() to check first
    create session time and method
    session.getLastAccessedTime() to check last access
    session time. I have to file
    showsession1.jsp
    When I open browser and run showsession1.jsp first
    time create and last time access is equal when I click
    link to showsession2.jsp it also equal. Why it still
    equal because it is second time that I access JSP
    file? It change when I refresh file showsession2.jspProbably showsession2.jsp was already in the browser cache and so there was no request to the server until you refreshed

  • Captcha, cookies and sessions

    I'm trying to make a http client to automate some tasks on a certain website. However, in order to be able to be able to do those tasks, I need to be logged in to that website. The site has captcha (random text in an image) protection. My question is: what would be the best way to do this? The image is generated from imagebuilder.php file and its a .png file. Should I use sockets? How could I make my client receive and send cookies?

    we're not going to help you circumvent systems designed to prevent scripkiddies like you from flooding using programs (which is what captchas are for).

  • Urgent: how to use cookies or session in javafx

    Hi....
    i am new to javafx and need help to learn how to use cookies and session in javafx.i want to create a simple website using javafx.....
    Urgent reply is requested
    mufaddal

    Please correct me if I'm wrong: I think LiveConnect is not supported on IE, and Mozilla has plans to discontinue it.
    Didn't an earlier version of JavaFX allow access to the Applet instance, including the AppletContext? Seems to me, just generally, that JavaFX applets are hobbled unless they have that functionality available. Cookies are one example. Also applet parameters, hyperlinks, and the browser status display.
    Especially hyperlinks.

  • Maintaining session both with cookies and jservsessionid

    Can the same session be maintained both with cookies and jservsessionid?
    If not, does anybody know how to link a request without cookie to an existing session? Can that be achieved by means of just the sessionid?
    Thanks,
    Modulab

    repost

  • Cookies, URL-Rewriting, and Sessions

    Hi All,
    I am aware that this is probably a question that has been asked many times in the past. Nonetheless, I have not been able to fully comprehend the differences. Therefore I would appreciate it, if someone could kindly spend some time explaining the differences between the three and when each would be the most preferred solution. ( cookies, url rewriting and sessions )
    So far what I understand is that, cookies can be used to store small amounts of data not more than 4kb, and that most browsers can not accept more than 20 at a time.... but would it be correct to say that the data is stored within the http headers ?
    URL rewriting, on the other hand is a method which can be used if cookies have been disabled by a browser. The 'session id' is appended to the url, and used to remember the data. ( how ? ). Although, it does mean that the programmer has to be very careful and ensure that rewriting occurs everytime it is passed to the browser, including redirection. ( whatever that means ? )
    Http sessions, seem to be the best solution out of the three ( but if this is the case, why are cookies and rewriting still hanging around today ? And even being taught at universities ? ). Also, they work on top of cookies and if these have been disabled sessions will not work !! ....
    As you can see ( from the above ) I do not have a thorough understanding of the three methods, especially if it comes to specifying the differences between the three.
    I would appreciate an explanation.

    HttpSessions use cookies or url rewritting to pass the session id which the server uses to associate a particular session with a particular request. A well developed web application will be written to use url rewriting when a client has cookies disabled. That being said I yet to see such a web application and personally believe that few people still disable cookies.
    Cookies still have uses.
    Persistant cookies are used to store data that needs to persist between sessions. This data is stored by the browser in a text files and passed to the server in the header. An example of this would be a site that offers personalization would store the user's id so that each time the user accesses the site he would see his personalization without being required to log in. Yahoo is a good example.
    In memory cookies are stored in the browser's memory and is used to store temporary data that goes away when the browser closes. Again this data gets passed to the server in the headers. Temporary cookies can be used to pass data between seperate web applications runing on the same host where storing the data in the session will not because each application has it's own session.

  • Error: Could not get markup. The cookie or session is invalid or ...

    When I run the portlet getting the below error:
    Error: Could not get markup. The cookie or session is invalid or there is a runtime exception.
    I have gone through the log, it's processing the request.
    Any help on this ...

    first can you give us some idea about which product/component/platform/version are you working with. and how did you edit the 'portal prefs'.
    thanks!

  • Acess "set-cookie" and set later in lookup in UDF?

    Hello Experts,
    I' have a senario where I need to get a session ID in order to handle a series of web service request. Therefore I have written a UDF in the mapping where the first method (as login message) where I get a login key as payload and the session-id in the response header. This session Id then needs to be set before several other calls within the same udf are made to the webservice. We are not able to use the Axis-adapter and therefore have to use the normal SOAP-adapter.
    My question now is, is there any way to access the header of the first response message? I need to read the returned session-id and then write it to the other requests. Any idea?
    regards
    Christian

    Hi Mark,
    for sure I can post the UDF. This UDF that I have written is a generic UDF that I call from several other UDF's where ever I need to create a lookup:
    AbstractTrace trace = container.getTrace();
    String returnValue = "";
    try {
      Channel channel =  LookupService.getChannel(party,communicationComponent, communicationChannel);
      SystemAccessor accessor = LookupService.getSystemAccessor(channel);     
      InputStream inputStream = new ByteArrayInputStream(requestXMLString.getBytes());
      XmlPayload payload = LookupService.getXmlPayload(inputStream);
      Payload SOAPOutPayload = null;  
      /*The SOAP call is made here and the response obtained is in the SOAPOutPayload.*/     
      SOAPOutPayload = accessor.call(payload);   
      /* Parsing the Returnvalue     */
      InputStream inp = SOAPOutPayload.getContent();     
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
      /* Build DOM Structure for Input XML */     
      DocumentBuilder builder = factory.newDocumentBuilder();     
      Document document = builder.parse(inp);  
      /* Set the XML-Tag for the Response  */     
      NodeList list = document.getElementsByTagName(requestXMLValueTag);
      Node node = list.item(0);     
      if (node != null)
       node = node.getFirstChild();
       if (node != null)
        returnValue = node.getNodeValue();          
    } catch (Exception e)
      trace.addWarning("Error" + e);
    return returnValue;
    So within this function I need to access the set-cookie and then set it accordingly. If have you have any suggestions I'm very happy to hear about it.
    I don't think that I can use your link that you posted as I don't have a URLConnection-Object
    Can you show us your UDF? Maybe this blog can help:
    Simple Way to Get HTTP Response Header in Java • Crunchify
    regards
    Christian

  • I can't sign into my Youtube account on Firefox, but it works fine on Safari and Google Chrome. Deleting my web history, cookies, and etc didn't help. PLZ HELP!

    I click on sign in on Youtube.com and it takes me to the sign in page. I enter my information (correctly, duh) and then I am returned to the Youtube home page. I try to click Sign in again and the page is just refreshed. My account still exists bc I can reach it on Safari and Google Chrome, but I don't want to have to switch browsers. By the way the cookies ARE enabled, so Idk what the problem is.

    hello, please also make sure that in particular youtube.com & accounts.google.com are allowed to set cookies (at least for the session)...
    [[Give certain websites the ability to store passwords, set cookies and more]]

  • Multiple proxy servers and session replication

              Hi,
              I'm in the middle of testing the 5.1sp10 that I set up recently.
              Say I have PROXY1 and PROXY2, connecting to the object layer.
              First, I point my browser to https://PROXY1/application. I did some stuff there
              that updated the session. Then I pointed my browser to https://PROXY2/application.
              The session was not replicated. Is this a normal behavior?
              What I thought I did was simulate DNS round-robin. I thought since the cookie
              knows which is the master and slave servers, the proxy can read the cookie, and
              I can continue with the session. Do I have to actually setup the DNS to do this?
              Thanks.
              

    No, that did not simulate a round robin. The change in server invalidates
              (in this case, makes invisible) the cookie.
              In your hosts file, add (with the correct names/addresses)
              192.168.0.17 proxy1
              192.168.0.18 proxy2
              Peace,
              Cameron Purdy
              Tangosol Inc.
              Tangosol Coherence: Clustered Coherent Cache for J2EE
              Information at http://www.tangosol.com/
              "Rudy" <[email protected]> wrote in message
              news:3c152f6d$[email protected]..
              >
              > Hi,
              >
              > I'm in the middle of testing the 5.1sp10 that I set up recently.
              >
              > Say I have PROXY1 and PROXY2, connecting to the object layer.
              > First, I point my browser to https://PROXY1/application. I did some stuff
              there
              > that updated the session. Then I pointed my browser to
              https://PROXY2/application.
              > The session was not replicated. Is this a normal behavior?
              >
              > What I thought I did was simulate DNS round-robin. I thought since the
              cookie
              > knows which is the master and slave servers, the proxy can read the
              cookie, and
              > I can continue with the session. Do I have to actually setup the DNS to
              do this?
              >
              > Thanks.
              

  • Open new browser window  and session

    My application A is launched from other application B.
    User first login to B, B has a link to A, when user clicks on link to A I open a new browser with the url for A , A creates a new session etc.surprisingly when user logs out in A session in B also expires and vice versa , please suggest me how to have different session when one browser opens a new Browser for a new application.

    The problem here is: browser is sharing session with new window. And moreover different browsers behave differently creating/sharing sessions in case of new tab, new window etc.
    Try URL rewriting instead of cookie for session management. Not sure whether this solves the problem.
    Please have a look here .
    Thanks,
    Mrityunjoy

  • Cache, cookies and history are not clearing when I close Firefox even though they are set to do so and have been for ages

    I recently had an update (or upgrade?) for FF 16. Today (and I believe the update was done a day or two ago?) my cache, cookies and history are not clearing when I close FF. Also, certain links are not working. Not links for full web pages but for site pop-ups (like the smilie window on a message board). They worked a few days but are not working today. I click the link and nothing happens. I noticed the problem with the cookies not clearing for a few weeks ago but it was only on one site not all sites which is what's happening now.
    My apologies if that's a little confusing. Thanks!

    At any rate, have you tried running Firefox in Private Browsing mode? This will ensure that no infromation from your session is saved once you exit Private Browsing mode and/or exit Firefox.
    You can set Firefox to always start in Private Browsing mode: https://support.mozilla.org/en-US/kb/private-browsing-browse-web-without-saving-info#w_how-do-i-always-start-firefox-in-private-browsing

  • Disable user and session tracking?

    Hi there?
    We would like to use Application Insights for everything except user and session tracking.
    How can i disable these features in AI (we may not use cookies in our site)?
    My guess is to change the applicationinsights.config file as below. Is there any documentation about the configuration file, right now im only guessing...
    Cheers
    /Niclas
    <?xml version="1.0" encoding="utf-8"?>
    <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">
    <!--
    Learn more about Application Insights configuration with ApplicationInsights.config here:
    http://go.microsoft.com/fwlink/?LinkID=513840
    -->
    <TelemetryModules>
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.RuntimeTelemetry.RemoteDependencyModule, Microsoft.ApplicationInsights.Extensibility.RuntimeTelemetry" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCollector.PerformanceCollectorModule, Microsoft.ApplicationInsights.Extensibility.PerfCollector" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.WebApplicationLifecycleModule, Microsoft.ApplicationInsights.Extensibility.Web" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.TelemetryModules.WebRequestTrackingTelemetryModule, Microsoft.ApplicationInsights.Extensibility.Web" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.TelemetryModules.WebExceptionTrackingTelemetryModule, Microsoft.ApplicationInsights.Extensibility.Web" />
    <!-- <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.TelemetryModules.WebSessionTrackingTelemetryModule, Microsoft.ApplicationInsights.Extensibility.Web" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.TelemetryModules.WebUserTrackingTelemetryModule, Microsoft.ApplicationInsights.Extensibility.Web" /> -->
    </TelemetryModules>
    <ContextInitializers>
    <Add Type="Microsoft.ApplicationInsights.Extensibility.BuildInfoConfigComponentVersionContextInitializer, Microsoft.ApplicationInsights" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.DeviceContextInitializer, Microsoft.ApplicationInsights" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.MachineNameContextInitializer, Microsoft.ApplicationInsights" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.AzureRoleEnvironmentContextInitializer, Microsoft.ApplicationInsights.Extensibility.Web" />
    </ContextInitializers>
    <TelemetryInitializers>
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.TelemetryInitializers.WebOperationNameTelemetryInitializer, Microsoft.ApplicationInsights.Extensibility.Web" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.TelemetryInitializers.WebOperationIdTelemetryInitializer, Microsoft.ApplicationInsights.Extensibility.Web" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.TelemetryInitializers.WebUserTelemetryInitializer, Microsoft.ApplicationInsights.Extensibility.Web" />
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.TelemetryInitializers.WebSessionTelemetryInitializer, Microsoft.ApplicationInsights.Extensibility.Web" />
    </TelemetryInitializers>
    </ApplicationInsights>

    I'm not sure if we have a documentation about this somewhere yet. But your guess was right. You can remove 2 modules and AI will not read and set cookies.
    Another option is to disable cookie setting but not reading. You would want this if you have JS SDK that sets cookies and you want Web SDK to read it and apply to server telemetry types.
    <Add Type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.TelemetryModules.WebSessionTrackingTelemetryModule, Microsoft.ApplicationInsights.Extensibility.Web" >
    <SetCookie>false</SetCookie>
    </Add>
    There are also 2 telemetry initializers for user and session. They take session and user from RequestTelemetry that was created by WebSdk and initialized in that modules and apply same session to other telemetry types like events and exceptions. If you cut
    modules you can cut telemetry initializers as well.
    Anastasia

  • Cookies and Firefox issue

    I am having an issue with my site (I did not develop it, but
    I am versed in CF enough to understand any solutions you might
    have)....
    Here is the problem...
    First, this is only an issue in Firefox. IE, Safari etc...
    etc.... do not have this problem.
    When you attempt to login, the page shows a message "Logging
    you in..." it then appears to be redirecting (as it should) to the
    requested page after successful login. But, it just flickers and
    then nothing. You are not logged in, no errors either from CF or
    from the code. Meaning there is nothing displayed to the user. So
    after a few tries users are giving up and leaving the site. What I
    have found is that if you clear the cookies then you can login and
    all is well.
    Upon further investigation, I logged into the admin side of
    the site, chose a user at random who had not logged in in more than
    a week. I tried to login to the site with his username and
    password, I could not (user and pwd are correct). After I could not
    login with his credentials, I tried my own and they too did not
    work although they did just prior to logging in with his. I cleared
    the cookies, and then it worked. (mine and his credentials).
    I also ttried, deleting just the cookies for my site and that
    doesn't work. It is only when you delete ALL cookies via the Clear
    Private Data, uncheck everything except cookies method that it
    works. So I'm stumped. I don't know if it is firefox, or my code,
    or the server, or IIS or what. Any clues that you folks can shed
    would be great. If anyone else is experiencing this sort of
    behavior please tell me what you have done. Again, I did not
    develop the site so technical details are a bit sketchy and I am
    trying to help the developer track this down.
    Essentially the site is developed in CF version 8, the login
    logic is CF/AJAX with javascript form field validation on the
    client. The webserver is IIS 6, the server itself is patched, the
    backend is SQL 2005 SP3 and again, this works flawlessly in other
    browsers.
    I appreciate any assistance.

    you said nothing about how your login framework is designed.
    are you using cflogin?
    did you make your own login framework based on session
    vars/whatever?
    are you using regular cf sessions or j2ee sessions? (you
    should do the
    latter, imho).
    let's start with that. post your code that performs login and
    the code
    that checks for login state. post you application settings as
    well.
    FF (as well as other browsers) has a feature to re-open
    previous tabs on
    start-up. this feature makes FF aggressively cache pretty
    much
    everything it can get its hands on, and never release it
    unless the user
    tells FF to clear out private data.
    your application needs to be designed with this and similar
    features in
    mind.
    post relevant code for starters.
    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com/

Maybe you are looking for