javaweb会话----->Session技术

一次会话中:多次请求。。。。
* 第一次连接请求到最后断开连接。。。都一直存在;或者服务器关闭。。。
* 解决问题就是:浏览器与服务器数据共享问题,request域的不足,会话技术拓展。。
* http每次请求和响应式无状态的。所以需要解决这个问题,,数据共享让每一次请求和响应变得有状态
* 会话技术就是让http的无状态,变成有意义的有状态
*
* 按照数据的存储情况把会话技术分为两种:
* 数据存储在服务器端:那就是Session技术
* 数据存储在浏览器端:那就是Cookie技术
服务器会话技术:
原理: Session的实现是依赖Cookie的

 

 

 

 

 

 

@WebServlet(urlPatterns = {"/session"}, loadOnStartup = 1)
public class SessionServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        //1  创建session对象
        //如果本次会话还没有session,那么这个就会创建一个session对象
        //如果本次会话中已经存在了session,那么就是获取已经存在的该session对象。。
        /*
        *
        * Session的实现是依赖Cookie的*
        * JSESSIONID:1479F7B045B3E185BAFDAB2A67DC2D39
        *它是服务器自动完成的。。
        *
        * 可以手动设置;
        * new Cookie("JSESSIONID","隔壁老郭")
        * */
        HttpSession session = req.getSession();
        session.setAttribute("key01", "郭XX");
    }
}

 

 

@WebServlet(urlPatterns = {"/cookieGet"}, loadOnStartup = 1)
public class CookieServletGet extends HttpServlet {

    /*会话技术Cookie技术:基于浏览器存储共享数据*/
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

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

        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ":" + cookie.getValue());
            //基于服务器的删除cookie
            cookie.setMaxAge(0);
            //如果添加的cookie的key重复,那么会覆盖之前的
            resp.addCookie(cookie);
        }


    }
}



posted on 2020-09-15 14:28  白嫖老郭  阅读(88)  评论(0)    收藏  举报

导航