一、什么是Session?
(1)服务器会给每一个用户(浏览器)创建一个Seesion对象;
(2)一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;

(3)用户登录之后,整个网站它都可以访问!-->保存一个登录用户的信息;·购物车信息.
二、Session和Cookie的区别:
(1)Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
(2)Session把用户的数据写到用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)

(3)Session对象由服务创建;
三、使用场景:
(1)保存一个登录用户的信息;

(2)购物车信息;
(3)在整个网站中经常会使用的数据,我们将它保存在Session中;
四、使用Session

package cn.edu.ccufe.servlet;

import cn.edu.ccufe.pojo.Person;

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

/**
 * @author jjx
 */
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中存东西
        session.setAttribute("name", new Person("xiaojing", 1));
        //获取Session的ID
        String sessionId = session.getId();
        //判断Session是不是新创建的
        if (session.isNew()){
            resp.getWriter().write("session创建成功,ID为:"+sessionId);
        }
        else {
            resp.getWriter().write("session已经在服务器中存在了,ID为:"+sessionId);
        }

        //Session创建的时候做了什么事情
       // Cookie cookie = new Cookie("JSESSIONID", sessionId);
        // resp.addCookie(cookie);


    }

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

五、得到Session

//得到Session
        HttpSession session = req.getSession();
        Person person = (Person) session.getAttribute("name");
        System.out.println(person.toString());

六、手动注销Session

HttpSession session = req.getSession();
        session.removeAttribute("name");
        //手动注销session
        session.invalidate();

七、设置会话自动过期(web.xml)

<!--设置Session默认的失效时间-->
    <session-config>
        <!--1分钟后Session自动失效,以分钟为单位-->
        <session-timeout>1</session-timeout>
    </session-config>

 

posted on 2022-04-24 21:31  山与月  阅读(37)  评论(0编辑  收藏  举报