Question & Answer
Question
Answer
By default, a cookie is sent only to the server from which it originated. If you are in a position where you are trying to send cookies across multiple servers (like in a simple single sign-on solution) you will need to explicitly set the Cookies Domain.
Following is a code snippet you can drop in a JSP page to achieve this.
Note: http://localhost, http://myServer, and http://myServer.mydomain.com are all in separate domains as far as the browser is concerned. You can not set a single cookie to span domains. If you need to do so, set multiple cookies, one for each domain. When comparing domains, the browser does a very literal string compare of the host portion of the URL to determine the domain. It does not "know" that localhost or myServer are also in "mydomain.com"
Following is a sample JSP to set a cookie to span across a domain:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
String myUserId = request.getParameter( "userId" );
if( myUserId == null )
myUserId = "Guest";
// Creates an aasremoteuser cookie
Cookie aasUsernameCookie = new Cookie( "aasremoteuser", myUserId );
// this cookie will work across all servers in the domain db2alphablox.ibm.com
aasUsernameCookie.setDomain( ".db2alphablox.ibm.com" );
// this cookie will be sent to all applications under the entire server
aasUsernameCookie.setPath( "/" );
// put the cookie in the response
response.addCookie( aasUsernameCookie );
// "automagically" redirect the user to a page on the new server
response.sendRedirect( "http://testsever2.db2alphablox.ibm.com/test/snoop.jsp" ); %>
Following is an excerpt from a snoop.jsp to check the value of the cookies that are set.
The cookies passed in this request are:
<%
Cookie cookies[] = request.getCookies();
for (int i = 0; i < cookies.length; ++i)
{
out.println (
"
" + cookies[i].getName()
+ " = " + cookies[i].getValue()
+ " (" + cookies[i].getDomain() + ")" );
}
%>
Was this topic helpful?
Document Information
Modified date:
21 July 2021
UID
swg21176874