On the
- cookie: client technology (response request)
- session: server technology, the use of this technology, you can save the user's session information? We can put information or data in the Session!
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的vlaue
new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie的有效期
resp.addCookie(cookie); //响应给客户端一个cookie
cookie: usually stored in the local user directory appdata;
- A Cookie can only save a message;
- A web site can send multiple cookie to the browser, cookie store up to 20;
- Cookie size is limited 4KB;
- 300 browser cookie limit
encode decode
URLEncoder.encode("秦疆","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")
What is Session:
- Server will give each user (browser) to create a Seesion objects;
- A Seesion exclusively a browser, as long as the browser is not closed, the Session there;
- After the user logs in, it can access the entire site! -> Save user information; save the cart information ......
Session and cookie difference:
- Cookie is the user data addressed to the user's browser, the browser stores (can save more)
- Session data is written to the user's user exclusive Session, the server-side save (save important information, reduce waste server resources)
- Session object is created by the service;
scenes to be used:
- Save a user's login information;
- Shopping Cart information;
- Data is often used throughout the site, we will save it in the Session;
Session automatically expires: web.xml configuration
<!--设置Session默认的失效时间-->
<session-config>
<!--15分钟后Session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>