Using cookies in servlet

Am setting up a cookie in my servlet as follows:
String sessionID = (String) session.getId();
Cookie info = new Cookie("userData", sessionID);
response.addCookie(info); response.sendRedirect(response.encodeRedirectURL("http4://localhost:8084/root/welcome.jsp"));
When i direct the response to the URI shown, the welcome.jsp does not see the cookie. This is the codes i have used in the jsp:
<%
String cookieName = "userData";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies;
if (cookieName.equals(cookie.getName())) {
String mycookie = cookie.getName();
//doSomethingWith(cookie.getValue());
%>
The servlet is called by a https page and i wnat to direct the cookie to http page. Where am i going wrong?
Thanks in advance.
M.

Cookies are domainspecific. Likely you've redirected
the page to another domain.hi BalusC,
I don't think so coz am redirecting to the same domain. If i use RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp"); rd.forward(request, response);
it works fine but i would like to sent the servlet to another protocol, http. Initially was https.

Similar Messages

  • Cant use cookies in servlet

    I can't use cookie in my Servlet upon Tomcat.
    When I reach the statement "cookies.length" in code a NullPointerException is generated.
    Logfile according to:
    2003-05-22 02:51:55 StandardContext[pk]: Reloading this Context is completed
    2003-05-22 02:51:55 HTMLManager: list: Listing contexts for virtual host 'localhost'
    2003-05-22 02:52:03 StandardWrapperValve[pk]: Servlet.service() for servlet pk threw exception
    java.lang.NullPointerException
    at calender.pk.doGet(pk.java:34)
    I guess my problem might be that cookies is not enabled but I can't solve it.
    My web.xml is :
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app>
    <servlet>
    <servlet-name>pk</servlet-name>
    <servlet-class>calender.pk</servlet-class>
    <init-param>
    <param-name>Cookies</param-name>
    <param-value>True</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>pk</servlet-name>
    <url-pattern>/pk</url-pattern>
    </servlet-mapping>
    </web-app>

    Here is my code. The problem occurs when deplying onto tomcat4.1.10. When running servlet from DevelopmentEnvironment(JBuilder5) everything works fine.
    package calender;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class pk extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html";
    private static final String STARTPAGE = "startpage";
    private static final String LOGIN = "login";
    private static final String CHECK = "check";
    private static final String USERNAME = "username";
    private static final String WELCOME = "welcome";
    private String welcome = "false";
    int responseCode;
    public void init() throws ServletException {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Debugger.debug("get start");
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    String function = request.getParameter("function");
    Cookie cookies[] = request.getCookies();
    String username = "";
    Actionhandler handler = new Actionhandler();
    for(int i=0;i<cookies.length;i++){
    Debugger.debug("cookieloop i get");
    if(cookies.getName().equals("welcome")){
    welcome = cookies[i].getValue();
    }else if(cookies[i].getName().equals("username")){
    username =cookies[i].getValue();
    if(welcome.equals("true") && username != null && username != ""){
    if(function != null){
    if(function.equals("add_worker_to_happening") ||
    function.equals("remove_all_workers_from_happening")||
    function.equals("change_to_status_ready")){
    handler.setHc_id(Integer.parseInt(request.getParameter("hc_id")));
    }else if(function.equals("remove_worker_from_happening")){
    handler.setWh_id(Integer.parseInt(request.getParameter("wh_id")));
    }else if(function.equals("remove_happening")){
    handler.setH_id(Integer.parseInt(request.getParameter("h_id")));
    responseCode = handler.getPage(request, response, username, function);
    }else{
    responseCode = handler.getPage(request, response, username, STARTPAGE);
    }else{
    responseCode = handler.getPage(request, response, username, LOGIN);
    if(handler.getHTML() == null){
    handler.getResponse().getWriter().write("no output");
    else handler.getResponse().getWriter().write(handler.getHTML());

  • Is there a way of not using cookies or "customized" url's? (servlets+jsp)

    Hi there.
    I'm wondering if there's an already implemented way of establishing a session without using cookies or url withs session id variables. Maybe it's possible uging IP to know wich computer is connected along with something else.

    Actually, I don't hace any requierements to use only IP but I'm learning to develop web apps in general and this is a doubt I've been having for a while.
    I guess IP+browser+screen res.+something else could work.
    Someone would possibly want to use this so the browser user, even with some skills wouldn't know he's being tracked.
    Maybe I have this doubt because I always hear about all the tracking done by companys for several purposes. But I'm not sure.
    Anyway, all this started when I started reading about sessions and users loging in.
    Now. My real doubt is: What kind of tracking should be used and how should it be done?

  • How to use Cookies in Web DynPro?

    Hello,
    Is there a way to use Cookies in Web DynPro like a regular Servlet uses in it's response Object?
    If yes, I could use a code example...
    Roy

    Hi Roy,
    1. This will create a Request Objec containing all the client's request just like in a regular Servlet or does it have special considerations I should worry about?
    A: If you have portal and webdynpro components, both have to use the same runtime. If you are using only webdynpro components then you can use the "Task" class. But it is a non-standard API.
    Task.getCurrentTask().getWebContextAdapter().getHttpServletRequest()
    2. Where do you recommend putting this statement? I assume at the wdDoInit() method right?
    A: Don't put this statement in the doInit(), if you are handling some event within the component and refreshes the view, your doInit() will not get executed.
    3. Is there a Response object I can create as well?
    A:
    HttpServletResponse response =((com.sap.tc.webdynpro.services.sal.adapter.core.IWebContextAdapter) WDWebContextAdapter.getWebContextAdapter()).getHttpServletResponse()
    Regards,
    Santhosh.C

  • How to use cookie in OAF?

    Hi,
    I want to set cookies from OAF controller.
    Any thought or code snippet?
    Abdul Wahid

    Thanks keerthi,
    Late reply.I guess, the article is about how oaf foundations is maintaining states.
    I did try search, but didn't get any direct solution to use cookies just like its used in servlets.
    The requirement was to maintain session information above the user level sessions. Custom servlet cookies looked fine, but couldn't get way to set those in OAF.
    However, if some body gets similar requirement, the solution found, was, "pageContext.putSessionValueDirect" method.
    Thanks again brother.
    Abdul Wahid

  • Deleting Cookies from Servlet

    hi
    i am working on JDeveloper 11.1.2.3
    i made a servlet filter and it works well but the problem is in the cookies ... i tried to delete the cookies from the servlet but in vain
    i uses this code but it does not work
    cookie.setMaxAge( 0 );
    Thanks

    Hi,
    Check
    http://stackoverflow.com/questions/3466267/problem-removing-cookie-in-servlet
    http://stackoverflow.com/questions/9821919/delete-cookie-from-a-servlet-response

  • Session Cookie in Servlet

    Hi all
    I have a issue please answer me.
    If users disabled cookies.( other than session cookies)
    how i should dynamically switch session cookies.
    and how i can generate session cookies in servlet?
    thanks
    yashvant

    If the user has cookies disabled (session, since persistent ones are rarely used for maintaining session state with a browser), then most containers will attempt 'url-rewriting' and insert the session uid there (in the URL). That should work even if cookies are disabled. In order to access a session, you simply call HttpServletRequest#getSession(). If no session exists, one will be created, else the existing one will be retrieved. The J2EE container will send either a cookie in the response or re-write the URL. You don't have to do anything special.
    - Saish

  • Using cookie with DII

    Here is an example to use cookie with static web service call:
    http://download.oracle.com/docs/cd/B32110_01/web.1013/b28974/j2sewsclient.htm#DAFDHCFA
    could some one give an example using cookie with dynamic invocation interdace to inva=oke web service?
    Thanks

    Dear net pas,
    Hope you are doing good.
    You have raised a very valid issue.
    Please do have a look at the SAP NOTE: 1144722-Global configuration of session cookies and attributes
    Also:
    Protecting Sessions Security
    http://help.sap.com/saphelp_nw70/helpdata/en/44/691ccdce2a3675e10000000a114a6b/frameset.htm
    Here pay special attention at:
    cookies named JSESSIONID (in accordance with the JavaÔ Servlet 2.3 specification) for tracking Web browser sessions.
    For this purpose, make sure that the value of SystemCookiesDataProtection and SystemCookieHTTPProtection properties of the HTTP Provider Service on the server nodes is set to true:
    More info at:
    http://help.sap.com/saphelp_nw70ehp2/Helpdata/EN/44/691ccdce2a3675e10000000a114a6b/content.htm
    Thank you and have a nice day :).
    Kind Regards,
    Hemanth
    SAP AGS

  • How to upload more than 100mb in using com.oreilly.servlet package

    hi all,
    I use com.oreilly.servlet package to upload and i use the following code to upload
    MultipartRequest mr = new MultipartRequest(request,"/tmp/saved",0x10000000);My problem is i can't upload more than 25mb, uploads upto 25mb and shows page cannot displayed err in IE,
    Pls help

    In the webserver there is most likely a configuration option for the maximum size that a request may have. So search through the manual of your particular webserver on how to change that.

  • How do I use cookies to control which part of the timeline to play from?

    Hi there,
    I have created an animation with Adobe Edge. My site uses Concrete5 and I am pulling in the Edge content into an IFRAME on my home page (there my be a better way to do this and I'm open to suggestions). I want the animation to play from the start when someone first visits the site, but if during their browser session they navigate back to the home page, I want the animation to only play a shorter segment of frames near the end.
    My question is, how do I use cookies to acheive this? I'm new to javascript/jquery.
    I've included the following code on compositionReady, (found in another post on this forum) but don't have a clue how to continue...
    // insert code to be run when the composition is fully loaded here yepnope(   {     nope:[       '/js/jquery.cookie.js'     ],   complete: init   } ); function init() { //create your cookie's initial values here } 
    My temp site is here - http://79.170.40.43/nutcrackerdesign.co.uk/
    On revisting the homepage, I only want to play from when the green 'How can we help?' button drops in.
    Many thanks!
    Russ

    Hi, Russ-
    I found this article, which seemed really helpful in describing how cookies work in JavaScript:
    http://www.quirksmode.org/js/cookies.html
    Remember that JS works just fine within Animate, so on your compositionReady, you can read your cookie and then set the play based on that.  You should probably uncheck the autoplay for your Stage and control the play of your Stage from the compositionReady.
    Good luck!
    -Elaine

  • Using cookies and JavaScript to create a page to page timer.

    I have long wanted to be able to measure the time it takes to get from one page to another.  While reading in my JavaScript reference the other day, I came across cookies.  I've long known about cookies but have never used them.  The thing that looked attractive was that you can access cookies from both JavaScript and CF.
    So I put together the procedures to store the "start time" (startTimeP8D) for the transition and activated it on the onUnload event of a 1stpage.  After a few rewrites I got it working.   Here is the JavaScript to do that: it consists of two functions: doTimer which is the input section and setCookie, which writes to the cookie.  Not the two numbered alert statements.
    doTimer - results for "start" from the doTimer function called from page 1 when it unloads. (See doTimer below)
         Please note that the two startTime8D values are the same immediately after they are stored.
    On the 2nd page in the sequence, I run the corresponding code to determine the "end time", compute the delta and write it out to the page.  It didn't all run on the first try, but it now seems to be running without a crash, which can be misleading.
          second set of outputs from page 2:    
         Please not that while the endTimeP8D match, the startTimeP8D value no longer matches the previously stored value. 
    There is one major hitch in the get along which has me stymied:  As you can see, when you compare the startTimeP8 in the setCookie – results above and the "startTimeP8" in the doTimer results below the startTimeP8 is not the value that I wrote to the cookie @ unload of page 1.  I have checked and checked and do now see anywhere that the startTimeP8D value is being overwritten.  Based upon my limited experience with JavaScript cookies, it seems to me that you get an entry for each time you set the cookie.  So I would expect to see to startTimeP8D entry for each setCookie event, not a different value.
         The result of the failed computation is shown on the bottom of the page.  As you can see, the Total Elapsed Time is negative, which is never a good sign.  The other time shown, Page build time, is the run time from the server.  The whole purpose is to be able to show folks that the reason the code might be show is because of their overloaded network and not our code.  We had one client whose had users running on 56k modems.  It was so slow their VPN software was timing out!!!  Still the had the never to blame us!!!
    I am using SQLServer 2005, CF8, IE8 on W7. 
    I'm not married to this way of doing this so if anyone has a better/easier way of doing a "page to page timer", I'm up for it.  I'd prefer to fix this one since I've been working on it for the past 3 days.
    Thanks in advcance for your help.
    Len, PHRED SE

    Here it is with no JQuery or console logging calls using cookie utility functions found here:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
           "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
         <title>Test JavaScript Page Load Timer</title>
         <script>
              window.onload = function(){
                   var previousPageUnload = getCookie('unloadTime');
                   if(previousPageUnload){
                        var d = new Date();
                        var loadTime = d.getTime() - previousPageUnload;
                        alert(loadTime + 'ms');
              window.onunload = function(){
                   var d = new Date();
                     setCookie('unloadTime',d.getTime());
              function setCookie(c_name,value,expiredays) {
                   var exdate=new Date();
                   exdate.setDate(exdate.getDate()+expiredays);
                   document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
              function getCookie(c_name) {
                   if (document.cookie.length>0) {
                     c_start=document.cookie.indexOf(c_name + "=");
                     if (c_start!=-1)
                       c_start=c_start + c_name.length+1;
                       c_end=document.cookie.indexOf(";",c_start);
                       if (c_end==-1) c_end=document.cookie.length;
                       return unescape(document.cookie.substring(c_start,c_end));
                   return null;
         </script>
    </head>
    <body>
         <h1>Test JavaScript Page Load Timer</h1>
    </body>
    </html>
    Note that overwriting global window events like this is not a good idea, which is why I used JQuery in my earlier example. I strongly suggest you look at JQuery or one of the other JS libraries (YUI, etc.) to help with event handling. I'll leave it at that as this is getting into JavaScript development, not really on topic for a ColdFusion forum.

  • How can i upload a image file to server by using jsp or servlet.

    Hi,
    I m gurumoorthy. how can i upload a image file to server by using jsp or servlet without using third party API. pls anyone send me atleast outline of the source code.
    Pls send me anyone.
    Regards,
    Gurumoorthy.

    I'm not an applet programmer so I can't give you much advice there.
    If you want to stream the file from the server before it's entirely uploaded, then I don't believe you can treat it like a normal file. If you're just wanting to throw it up there and then listen to it, then you can treat it like a normal file.
    But again, I'm not entirely certain. You might be able to stream the start of the file from the server while you're still uploading the end of it, but it probably depends on what method you're using to do the transfer.

  • Need a good charting library (for use in a servlet/jsp environment)

    Anyone know of a good charting library for use in a servlet/jsp environment.

    Use JFreechart combined with cewolf.
    www.object-refinery.com/jfreechart/
    To use charts in a jsp page you can use cewolf ( a taglib) based on jfreechart.
    http://cewolf.sourceforge.net/
    Both are free.

  • How to use JNI with Servlets

    Hi
    i was trying to do some example with JNI. I can use JNI with standalone Java application but I just cannot figure out how I can use JNI with Servlet.
    Can some one show me a sample code using JNI with Servlets.
    thanks very much

    hi,
    I am also facing the same problem,
    when I am using JNI with stand alone application it works fine but when i tried to use it with a servlet It gives unsatisfied linker error
    stack: java.lang.UnsatisfiedLinkError: createSocket
         at RelayConnector.createSocket(Native Method)
         at RelayServlet.doGet(RelayServlet.java:70)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.iplanet.server.http.servlet.NSServletRunner.invokeServletService(NSServletRunner.java:891)
         at com.iplanet.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:458)
    It seems i have to do some path settings in my iplenet web server.
    If some one have faced the problem i would be glad to know the solution for this, i am literally bugged up,....

  • Can we use threads in servlets

    Hi,
    can we use threads in servlets.
    cheers
    Sen

    You can also use java.io.Serializable at the end of you class
    eg:
    public class MyClass implements java.io.Serializable{

Maybe you are looking for