Series of articles
JavaWeb Development 01-Basic Concepts, Web Server, HTTP, Maven
JavaWeb Development 03-Cookie and Session
JavaWeb Development 05-Filters, Listeners
JavaWeb Development 06-smbms project practice
Article Directory
6、Cookie 和 Session
There are a few nouns that need to be understood first.
Session : After the user opens a browser, clicks on some hyperlinks to access multiple Web resources, and then closes the browser. This process is called a conversation.
Stateful session : When a user visits for the second time, the server knows that the user is visiting for the second time. Because the server marked the user for the first time (or the user registered on the server).
How does a website prove that the user is visiting for the second time?
- When the client (browser) visits for the first time, the server gives the client an identity, and the client will show the identity when visiting again later. This is Cookie (Chinese Cookies).
- When the user visits for the first time, he goes to the server to register, and when the user visits later, the server checks the register. This is Session (Chinese is conversation).
From the above, we can know that Cookie is a client technology, and Session is a server technology. Because the Cookie is the client that needs to carry to identify its identity when accessing the Web, and the Session is for the server to query its own register. These technologies for saving a session are often used to log in. For example, we have logged in to the browser once on Taobao, and there is no need to enter the account and password when logging in later.
Demonstrate separately below.
6.1、Cookie
- A Cookie can only store one piece of information (key-value pair method)
- A website can send multiple cookies to the browser, and the size of each cookie is also limited
- Cookie data is saved by the browser itself
- Delete cookies
- If you don’t set an expiration date, it will automatically expire after closing the browser
- Set the validity period to 0 and expire immediately
CleanServlet.java
@WebServlet(name = "CleanServlet", urlPatterns = "/cleanCookie")
public class CleanServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(
HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
cookie.setMaxAge(0);
response.addCookie(cookie);
cookie = new Cookie("firstLoginTime", System.currentTimeMillis()+"");
cookie.setMaxAge(0);
response.addCookie(cookie);
response.getWriter().write("清理Cookie");
}
}
TestCookie.java
package com.zcy.servlet;
@WebServlet(name = "TestCookie", urlPatterns = "/cookie")
public class TestCookie extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码,无论是响应还是请求
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//从客户端获取Cookie,所以用请求对象,且一个客户端可能有多个Cookie,返回数组
Cookie[] cookies = req.getCookies();
boolean flag = true;//标志位
//判断自定义的Cookie是否存在(默认就会有两个Cookie)
for (int i = 0; i < cookies.length; i++) {
// 如果存在名为上次登录时间的Cookie
if (cookies[i].getName().equals("lastLoginTime")){
Date date = new Date(Long.parseLong(cookies[i].getValue()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out.println("你上次登录的时间:"+sdf.format(date));
flag = false;
}
//如果存在名为第一次登陆时间Cookie
if (cookies[i].getName().equals("firstLoginTime")){
Date date = new Date(Long.parseLong(cookies[i].getValue()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out.println("你第一次登录的时间:"+sdf.format(date));
flag = false;
}
}
if (flag){
out.write("这是你第一次访问");
//第一次登录的时间
Cookie cookie = new Cookie("firstLoginTime", System.currentTimeMillis()+"");
//设置Cookie的有效期为1天,单位秒
cookie.setMaxAge(24*60*60);
//发放Cookie是服务器发给客户端,所以用响应对象
resp.addCookie(cookie);
}
//更新登录时间
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
}
result:
6.2, Session (emphasis)
- The server will create a session object for each user (browser)
- A session occupies a browser, as long as the browser is not closed, the session will exist (this is the case when the validity period is not set)
- After the user logs in, the entire website can be accessed! Used to save user information, shopping cart information, etc.
Two ways to log out of session:
session.invalidate();//手动注销,注销后会立即创建新session
//session也可以删除值
session.removeAttribute("name");
<!--在web.xml中规定时间,单位分钟-->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
TestSession1.java
class Person{
private String userName;
private String password;
public Person(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
}
@WebServlet(name = "TestSession1", urlPatterns = "/session1")
public class TestSession1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
Person person = new Person("张三", "123456");
//虽然这里是从请求端获取,但依然是服务器创建的Session。
HttpSession session = req.getSession();
session.setAttribute("person", person);
if (!session.isNew())
resp.getWriter().println("session已经存在,ID:"+session.getId());
}
}
TestSession2.java
@WebServlet(name = "TestSession2", urlPatterns = "/session2")
public class TestSession2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
HttpSession session = req.getSession();
writer.println("session ID:"+session.getId()+"<br/>");
Person person = (Person)session.getAttribute("person");
writer.println("用户名:"+person.getUserName()+",密码:"+person.getPassword());
}
}
result: