Session解决了Cookie记录量小,数量限制的问题,每个客户端有唯一的一个Session。
我们先往Session里放入数据
Session1
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("name");
HttpSession session =request.getSession();
session.setAttribute("name", name);
//不同的 session有 不同的id
response.getWriter().println(session.getId());
}
Session2
然后我们再从Session2里取出数据,当然是同一个客户端,浏览器也会有影响。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String value = (String) session.getAttribute("name");
out.println(value);
out.println(session.getId());
//request( 请求级别),ServletContext(应用), Session(会话级别)
}
当我们访问Session1时传入的数据不同,那么我们取出的数据也不一样。每个客户端有自己唯一的Session。
下面我们再看一下context的。context的特点就是它是共用的,所有的客户端都可以取出同一条记录
context1
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getServletContext().setAttribute("name", "lisi");
}
context2
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String value = (String) getServletContext().getAttribute("name");
response.getWriter().println(value);
}
只要设置过context1的值,那么所有客户端都可以访问context2取出值。