Cookies and sessions
Cookies and sessions
1. Conversation
Session: users open a browser, click many hyperlinks, access multiple web resources, and close the browser. This process can be called session
Stateful conversation: when a classmate comes to the classroom next time, we will know that the classmate has been here, which is called stateful conversation
Your school
How can you prove that you are a student of the school?
A website to prove that you have been here?
Client server
2. Two techniques for saving sessions
cookie
session
Common scenario: after the website is logged in, you don't need to log in next time. You can visit it directly the second time
3. Cookie
Cookie[] cookies = req.getCookies(); //获得cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的value
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis() + ""); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie有效期
resp.addCookie(cookie); //响应给客户端一个cookie
Cookie: appdata stored in the local user directory
Is there an upper limit for a website cookie? Talk about the details
Delete cookie
Encoding and decoding: when using Chinese, you may encounter the problem of garbled code (Tomcat version is lower). Use the following method for encoding and decoding (decode when using Chinese output and encode when using Chinese input)
URLEncoder.encode("汉字","utf-8") //编码
URLDecoder.decode(cookie.getValue(),"UTF-8") //对cookie中的value存放的汉字进行解码
4. Session (key)
What is a session:
The difference between session and cookie
Usage scenario
Using session
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
//解决乱码问题
resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new Person("名字",1));
//获取Session的ID
String sessionId = session.getId();
//判断Session是不是新创建的
if (session.isNew()){
resp.getWriter().write("session创建成功,ID:" + sessionId);
}else {
resp.getWriter().write("session已经在服务器中存在了,ID:" + sessionId);
}
//Session创建的时候做了什么事情
// Cookie cookie = new Cookie("JSESSIONID",sessionId);
// resp.addCookie(cookie);
}
@Override
protected void doGet(HttpServletRequest req,IOException {
//解决乱码问题
resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
Person person = (Person)session.getAttribute("name");
System.out.println(person.toString());
}
@Override
protected void doGet(HttpServletRequest req,IOException {
HttpSession session = req.getSession();
//手动注销Session
session.removeAttribute("name"); //要注销的Session的key
session.invalidate();
}
Session Expiration: Web XML configuration
<!--设置Session默认的失效时间-->
<session-config>
<!--1分钟后Session自动失效,以分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>