session的实例

1、
public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //解决乱码问题
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");
        resp.setContentType("text/html;charset=utf-16");
        //得到session
        HttpSession session = req.getSession();
        //给session中存东西
        session.setAttribute("name","秦疆");
        //获取session的ID
        String sessionId = session.getId();
        //判断session是不是新创建
        if(session.isNew()){
            resp.getWriter().write("session创建成功,ID:"+sessionId);
        }else {
            resp.getWriter().write("session已经在服务器中存在了,ID:"+sessionId);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
2、public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");
        resp.setContentType("text/html;charset=utf-16");
        //得到session
        HttpSession session = req.getSession();

        String name = (String)session.getAttribute("name");  //这个是上面那个name
        System.out.println(name);
    }

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

3、将要获取的name放在一个类对象中

session的实例_第1张图片

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

将1中的name修改为

session.setAttribute("name",new Person("秦疆",1));

将2中的String改为Person

Person person = (Person) session.getAttribute("name");

然后输出

System.out.println(person.toString());

4、设置失效时间

session的实例_第2张图片

5、

session和cookie的区别

cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)

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

session对象由服务器创建;

6、使用场景

保存一个登陆用户的信息

购物车信息

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

你可能感兴趣的:(session的实例)