Today test settings and get cookies have encountered a little problem, very strange problem;
Deploy the Java EE service on the local 8080 port; When accessing any one service, if the client does not have a cookie, the cookie is issued,
If the client already has the value of the cookie, it is not issued, the code logic is as follows:
String uid="";
Cookie mycookies[] = request.getCookies();
if (mycookies!= null) {
for (int i = 0; i < mycookies.length; i++) {
if ("uid".equalsIgnoreCase(mycookies[i].getName())) {
uid=mycookies[i].getValue();
}
}
}
if(!StringUtils.isNull(uid)){
//do nothing
}else{
String host=request.getHeader("host");
uid=UUID.create();
Cookie mycookie = new Cookie("uid",uid);
mycookie.setDomain(host);
mycookie.setMaxAge(93312000);//三年
response.addCookie(mycookie);
}
System.out.println("uid is>"+uid);
1, visit:
http://localhost:8080/
and the internal pages, the print UID values are the same;
2, visit:
http://127.0.0.1:8080
As well as the internal pages, UID each time to obtain the value is different;
The difference between the two is only the way the access is different, if using IP access
Cookie mycookies[] = request.getcookies (); The value of the UID is never obtained;
(excluding 80 port numbers)
Check the browser's specific cookie value, found
http://localhost:8080/access, the cookie value is placed under localhost, the server automatically generated SessionID is also stored in the localhost path.
When http://127.0.0.1:8080/access, the cookie UID value is placed under 127.0.0.1:8080, and the servlet on the cookie server at 127.0.0.1:8080 will never get , and the server automatically generated SessionID is under 127.0.0.1, unlike the UID storage location.
So when a cookie is issued at the service end,
String Host=request.getheader ("host");
Need to be modified to
if(host.indexOf(":")>-1){
host=host.split(":")[0];
}
or give up setting Mycookie.setdomain (host);
The cookie value is also saved under 127.0.0.1 and is not associated with the port number
Of course, the server already has domain name will not appear under the port number can not get the value of the cookie;