Servlets and Cookies

Hi I am trying to set a cookie in a servlet and redirecting the servlet to a static html page. In the html page I have javascript code which is unable to read the cookie set by the servlet. Quick help is appriciated

Note: Servlet is running on the WebSphere where webshpere on port 10200 and the HTML page is on the same server but on a different port 80

package com.dcx.media;

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class LDAPCookieTest extends HttpServlet implements SingleThreadModel {

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {

PrintWriter out = res.getWriter();

//sending the parameter to the servlet to which html page it should go to.

buildCookie(URLInfo,res,out);

}

public void buildCookie(String URLInfo,HttpServletResponse response,PrintWriter out) {

try {

Cookie cok = new Cookie("testProfile","ValuesoftheURL");

cok.setDomain(".chrysler.com");

response.addCookie(cok);

out.println("Cookie Value"+cok.getValue());

response.sendRedirect(http://host.chrysler.com:port/filename.html);

}

catch (Exception e)

{ }

}

}

HTML file filename.html is as follows

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

function getCookie(Name) {

var search = Name;

if (document.cookie.length > 0) {

offset = document.cookie.indexOf(search);

if (offset != -1) { // if cookie exists

offset += search.length+1;// set index of beginning of value

end = document.cookie.indexOf(";", offset)

// set index of end of cookie value

if (end == -1) end = document.cookie.length;

//alert("cookie :"+document.cookie.substring(0,end));

return unescape(document.cookie.substring(offset, end))

}

}

}

document.writeln("Cookie Value is "+getCookie("testProfile"));

</SCRIPT>

</head>

<html>

[2161 byte] By [srp15] at [2007-9-26 2:25:13]
# 1

I have been looking at your servlet code and concluded that the line:

response.addCookie(cok);

, would have actually send the "testProfile" cookie value to the client browser.

So, maybe the problem is with the Javascript you have on the HTML page itself.

Question: Can you post the output of this line in your Javascript?

document.writeln("Cookie Value is"+getCookie("testProfile"));

Allen Lai

SUN Developer Technical Support

allenlai at 2007-6-29 9:35:55 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
I found the problem I have to set the path for the cookie. When I set the path to root "/" then I am able to read the cookie from any of the html pages with in the same domain.Thank you very much for your help.Suneetha
srp15 at 2007-6-29 9:35:56 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...