core servlets 9.6

Cookie userCookie = new Cookie("user", "uid1234");

userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year

response.addCookie(userCookie);

 

HttpSession session = request.getSession();

Behind the scenes, the system extracts a user ID from a cookie or attached URL data, then uses that ID as a key into a table of previously created HttpSession objects. But this is all done transparently to the programmer: you just call getSession. If no session ID is found in an incoming cookie or attached URL information, the system creates a new, empty session. And, if cookies are being used (the default situation), the system also creates an outgoing cookie named JSESSIONID with a unique value representing the session ID. So, although you call getSession on the request, the call can affect the response. Consequently, you are permitted to call request.getSession only when it would be legal to set HTTP response headers: before any document content has been sent (i.e., flushed or committed) to the client.

 

response.encodeURL()这个函数是干什么用的?

它可以在对方浏览器不支持cookies时实现会话跟踪。 这个技术叫URL重写。

String originalURL = someRelativeOrAbsoluteURL;

String encodedURL = response.encodeURL(originalURL);

out.println("<A HREF=\"" + encodedURL + "\">...</A>");

类似的:

String originalURL = someURL;

String encodedURL = response.encodeRedirectURL(originalURL);

response.sendRedirect(encodedURL);

你可能感兴趣的:(Servlets,职场,core,休闲)