对于创建和获取Session,它们的API是一样的。
request.getSession()
isNew(); 判断到底是不是刚创建出来的(新的)
SessionServlet程序:
public class SessionServlet extends BaseServlet { protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建Session HttpSession session = req.getSession(); //判断Session是否为新创建的 boolean isNewSession = session.isNew(); //获取Session会话的唯一ID String sessionId = session.getId(); resp.getWriter().write("当前Session对象是否为新创建的:" + isNewSession + "<br/>"); resp.getWriter().write("当前Session对象的唯一ID值为:" + sessionId); } }
session.html页面:
SessionServlet程序:
/** * 往Session中保存数据 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().setAttribute("key1", "value1"); resp.getWriter().write("已经往Session中保存了数据"); } /** * 获取Session域中的数据 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object attribute = req.getSession().getAttribute("key1"); resp.getWriter().write("从Session中获取了key1的数据是:" + attribute); }
session.html页面:
SessionServlet程序:
/** * Session的默认超时时长 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); int defaultOutTime = session.getMaxInactiveInterval(); resp.getWriter().write("Session会话的默认超时时长为:" + defaultOutTime); }
session.html页面:
浏览器访问效果:
说明:
SessionServlet程序:
/** * 设置Session3秒后超时 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取Session对象 HttpSession session = req.getSession(); //设置当前Session3秒后超时 session.setMaxInactiveInterval(3); resp.getWriter().write("当前Session已经设置为3秒后超时"); }
session.html页面:
浏览器效果:
针对于上面的情况,我们需要对Session超时的概念做一个介绍:
SessionServlet程序:
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //先获取Session对象 HttpSession session = req.getSession(); //让Session会话马上无效 session.invalidate(); resp.getWriter().write("Session已经设置为超时(无效)"); }
session.html页面:
原文:https://www.cnblogs.com/897463196-a/p/13990746.html