package com.mahe666.servlet;

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 SessionTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");

        //得到Session
        HttpSession session = req.getSession();

        //给Session中存东西
        session.setAttribute("name","马赫666");

        //获取Session的ID
        String id = session.getId();

        //判断Session是不是新创建的
        if (session.isNew()){
            resp.getWriter().println("session创建成功，ID="+id);
        }else{
            resp.getWriter().println("session已经存在，ID="+id);
        }

        //获取Session中的内容
        //String name = (String) session.getAttribute("name");
        //System.out.println(name);

        //注销Session
        //session.invalidate();

    }

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