Javaweb--session

tech2022-10-24  107

Session(重点)

什么事session:

·服务器会给每一个用户(浏览器)创建一个session对象;

·一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在;

·用户登陆之后,整个网站它就可以访问!-》保存用户的信息,保存购物车的信息。。。。

session和cookie的区别:

·cookie是把用户的数据写给用户的浏览器,浏览器保存

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

·session对象由服务器创建

使用场景:

·保存一个登陆用户的信息

·购物车信息;

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

创建session:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //解决乱码问题 resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset-utf-8"); //得到session HttpSession session = req.getSession(); //给session中存东西 // session.setAttribute("name", "朴灿烈"); session.setAttribute("name", new Person("吴世勋",27)); //获得session的ID String id = session.getId(); //判断session是不是新创建的 if(session.isNew()) { resp.getWriter().write("session创建成功,ID:"+id); }else { resp.getWriter().write("session以及在服务器中存在了,ID:"+id); } // //session创建的时候做了什么事情: // Cookie cookie = new Cookie("JSESSIONID",id); // resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); }

获取数据

// TODO Auto-generated method stub //解决乱码问题 resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset-utf-8"); //得到session HttpSession session = req.getSession(); // String name = (String) session.getAttribute("name"); Person person = (Person) session.getAttribute("name"); System.out.println(person); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); }

会话自动过期:web.xml

<!-- 设置session默认的失效时间 --> <session-config> <!-- 1分钟后自动失效 --> <session-timeout>1</session-timeout> </session-config>

最新回复(0)