IBM Support

Setting a Domain Cookie in a .jsp page

Question & Answer


Question

This Technote includes the an explanation of, and code to be used, in setting a cookie to span servers within a domain in a .JSP page.

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"

Setting the Cookie

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" ); %>

Verifying the Cookie

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() + ")" );
}
%>

[{"Product":{"code":"SSCPX3","label":"DB2 Alphablox"},"Business Unit":{"code":"BU059","label":"IBM Software w\/o TPS"},"Component":"Java and Web Development","Platform":[{"code":"PF002","label":"AIX"},{"code":"PF027","label":"Solaris"},{"code":"PF033","label":"Windows"},{"code":"PF016","label":"Linux"}],"Version":"8.4;9.5","Edition":"","Line of Business":{"code":"LOB10","label":"Data and AI"}}]

Document Information

Modified date:
21 July 2021

UID

swg21176874