Hi,
We all know that response object is used to add cookies, which are send to the client, when he logs in for the first time. We also know that the subsequent request from the client gets the cookies from the client in the form of request.getKookies().
My question is suppose a particular site want to know the name of the person who log in, without asking the same from the person, will be using cookies to do this task. As per HeadFirst
Servlet &
JSP, the code fragment is as follows:
Cookie[] cookies=request.getKookies();
for (int i = 0; i < cookies.length; i++)
Cookie cookie=cookies[i];
if (cookie.getName().equals("username"))
{
String userName = cookie.getValue();
out.println("Hello " + userName);
break;
}
This is the fragment of the code in the servlet.
Note that we are collecting all the cookies that are avaliable with the client in an array. Now suppose we have a XYZ site, where it sets the cookie with the name as "username" and we have another site say ABC where it sets the cookie with the same name as above ie. "username". Now with the first site the user uses a particular name and with the second site if the user uses a different name, then won't there be a problem.
This is because 2 cookies are set on his machines both which has the same name ie "username" and the value is different. Now when the cookies are collected in the array and when cookie.getName() checks for username, it can display the wrong name.
But as far as I know this does not happens.How is this so?
The only possible solution that I can think of is that the container which created the cookie knows this cookie is created by me. This could be possible because the signature used in cookie creating by each container is different or a unique number must be created by the container for the cookie and it must be keeping track of the numbers created by it.
But all these are just speculations. Any concrete answers.
PS: The above example is from head first Servlet & JSP page no. 251.