关于session

·cookie是把用户的数据写给用户的浏览器,让浏览器来保存(可以保存多个)

·session把用户的数据写到用户独占的session中,服务端保存(保存重要的信息,减少服务器资源的浪费)

·session对象有服务器创建

 

session应用场景:

  ·保存一个登录用户的信息;

  ·购物车信息;

  ·在整个网站中经常会使用的数据,我们会将他保存到session中;

 

session小测试

   一·创建一个session

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemo01 extends HttpServlet {

@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");

//得到session
HttpSession session = req.getSession();
//给session中存对象
     //person是我自己创建的实体类
session.setAttribute("Person", new Person("吴大叔",1));
//获取sessionde ID
String id = session.getId();
//判断是否是新创建的
if (session.isNew()){
resp.getWriter().write("session创建成功,ID:"+id);
}else {
resp.getWriter().write("已经注册sessionID:"+id);
}

/*//session创建的时候做了什么
Cookie cookie = new Cookie("sessionID",id);
resp.addCookie(cookie);*/
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

二·得到session中的数据
public class SessionDemo02 extends HttpServlet {

@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");

//得到session
HttpSession session = req.getSession();
//获取name
Person sessionAttribute = (Person) session.getAttribute("Person");

resp.getWriter().write("获取name:"+sessionAttribute);

System.out.println(sessionAttribute);
/*//session创建的时候做了什么
Cookie cookie = new Cookie("sessionID",id);
resp.addCookie(cookie);*/
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}

} 三·删除session
public class SessionDemo03 extends HttpServlet {
@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");

//获取session
HttpSession session = req.getSession();
//=删除session中获取的数据
session.removeAttribute("Person");
//手动注销session,但是会形成一个新的id
session.invalidate();
//响应
resp.getWriter().write("session已删除");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}



posted @ 2021-10-22 12:12  吴大叔  阅读(33)  评论(0编辑  收藏  举报