Session技术入门代码案例

package com.loaderman.demo;

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


public class SaveServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.创建session对象
        HttpSession session = request.getSession();
        /**
         * 得到session编号
         */
        System.out.println("id="+session.getId());
        /**
         * 修改session的有效时间
         */
        //session.setMaxInactiveInterval(20);

        /**
         * 手动发送一个硬盘保存的cookie给浏览器
         */
        Cookie c = new Cookie("JSESSIONID",session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);
        //2.保存会话数据
        session.setAttribute("name", "rose");
    }

}
package com.loaderman.demo;

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 GetDemo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.得到session对象
        HttpSession session = request.getSession(false);

        if(session==null){
            System.out.println("没有找到对应的sessino对象");
            return;
        }

        /**
         * 得到session编号
         */
        System.out.println("id="+session.getId());

        //2.取出数据
        String name = (String)session.getAttribute("name");
        System.out.println("name="+name);
    }

}

运行,请求后,日志如下:

id=E6492321D1C1E6001E2B7DDCECE7106E

....

id=E6492321D1C1E6001E2B7DDCECE7106E
name=rose

 

posted on 2018-11-22 10:21  LoaderMan  阅读(170)  评论(0编辑  收藏  举报

导航