One way to solve the stateless http cookie features

the role of the cookie:
// cookie is a kind of user information stored in browser technology

cookie definitions:
// cookie: Create a small biscuit (cookie), servlet use it to send a small portion of the information to the browser, saved in the browser, and then returned to the server

 

First, be aware of two methods:

//request.getCookies();// acquisition request header information (on behalf of the server)
//response.addCookie(arg0);// set a response header (on behalf of the browser)


The following is the specific implementation steps:

//1.创建cookie
Cookie cookie = new Cookie("name","zhangsan");
Cookie cookie2 = new Cookie("productID","computer123456");

// 2 sends the cookie to the browser (the response to the browser cookie)
response.addCookie (cookie);
response.addCookie (Cookie2);


//3.获取浏览器端发送过来的cookie
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
System.out.println(cookies[i].getName() + "---->"+ cookies[i].getValue());
}
}

 

Of course, there are some common attributes cookie:

For example: 1.setMaxAge for the cookie set the maximum survival time :

// set a cookie if the maximum survival time, can save a cookie on your hard drive where the browser
// If you do not set the maximum survival time cookie, the cookie is saved in the browser's memory, close the browser that is released
cookie.setMaxAge (30 * 60); // in seconds, i.e., for half an hour
//cookie.setMaxAge(60 * 60 * 24 * 7) ; // week

2.setPath to set a cookie access path

// set a cookie access path (ie cookie want to access must enter this path, otherwise not visit)
cookie.setPath ( "/ demo03 / Cookie");

 

Note:
cookie commonly used in the cart or seven of these free secret log on, use is not particularly widespread,
but cookie is unsafe because it saved on the hard disk where the browser easily be stolen by hackers.

Guess you like

Origin www.cnblogs.com/su-chu-zhi-151/p/11199200.html