会话
会话:一个用户打开浏览器,浏览多个web页面之后,关闭浏览器。这个过程可以称之为会话。
有状态会话:用户浏览一个网站之后,下次再浏览时,这个网站知道他曾经来过,称之为有状态会话。
保存会话的两种技术
cookie:是一种客户端技术,服务器从请求中拿到cookle信息,再响应给客户端。(可以看做学生证,不同的是,cookle可以有多个)
Session:服务器端技术。用户访问服务器后,我们可以把信息或数据放在Session中。
cookle和session的区别
1.Cookle是把用户的数据写给用户的浏览器,浏览器保存。(可以保存多个)
Session是把用户的数据写到服务器端的Session中,服务器端保存。(保存重要的资源,减少服务器资源的浪费)
Session详解
含义:
1.服务器会给每个用户(这里的用户可以看做浏览器)创建一个Session对象
2.一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在。
3.用户登陆之后,整个网站都可以访问。
应用场景:
1.保存一个用户的登录信息。
2.购物车信息
3.整个网站会经常使用的数据,会将它保存在Session中。
使用Seesion
1.向Session中存入信息
package com.dz.session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class sessionDemo01 extends HttpServlet {
@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","zsq");
//获得Session的id
String id = session.getId();
if (session.isNew()){
resp.getWriter().write("session创建成功,id为"+id);
}
else
resp.getWriter().write("session已经存在,id为"+id);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.从Session中获取用户信息
//得到Session
HttpSession session = req.getSession();
//获得Session存入的信息
String name = (String) session.getAttribute("name");
System.out.println(name);
3.删除Session中的信息,并注销Session
//通过浏览器端(请求)获取session
HttpSession session = req.getSession();
//将信息删除
session.removeAttribute("name");
//注销session
session.invalidate();
在web.xml配置Session自动失效时间
<session-config>
<!-- 以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
详细内容请点击这里。