会话跟踪技术-Session

2018-01-02  本文已影响0人  红Archer

session
作用
实现同一个客户端,不同请求之间的数据传递

数据放在WebServer中的HttpSession对象中
1、每个客户端对应一个唯一的Session对象
2、setAttribute(String,object)
Object getAttribute(String)
request,getSession()
getSession(boolean)

web.xml中设置session生命周期3分钟
<session-config>
<session-timeout>3</session-timeout>
</session-config>

protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object userName = session.getAttribute("userName");
        session = req.getSession(true);
        //保证肯定会返回一个Session对象
        session = req.getSession(false);
        //有可能返回null
        System.out.println(userName);
        session.setAttribute("userName", "张三");//放和拿都在服务器中不存在转码问题
        String id = session.getId();//session ID
        System.out.println(id);
        session.setMaxInactiveInterval(300);//session生命周期 单位秒
        //session.invalidate();//让session立马结束生命周期
        PrintWriter out = res.getWriter();
        String url = res.encodeRedirectURL("sessionServlet");
        //url重写,传递sessionID
        System.out.println(url);
        out.print("<a href='"+url+"'>111</a>");
    }

当Cookie被禁用的时候可以使用URL重写进行传递SessionID来实现session

String url = res.encodeRedirectURL("sessionServlet");
        //url重写,传递sessionID
        System.out.println(url);
        out.print("<a href='"+url+"'>111</a>");
上一篇 下一篇

猜你喜欢

热点阅读