session的相关知识与用法

一、session:setAttribute() 作用域?

答:一次会话

PS:会话就是浏览器与服务器之间的一次通话,可以在多次请求中保存和使用数据。

 

session 为服务器端使用的,记录客户端状态的机制;

可用方法 session.getId(); 获取

不是所有信息都要放到session里,把关键用到的放进去即可,例如用户名。

一个浏览器只可以存在一个用户,一个session,可多页面共享,保存在服务器端。

 

二、session 的生命周期:

1.主动清除session,即:注销等动作。

(一)设置会话失效:session.invalidate();

    在首页登陆后,在用户名后添加一个超链接,名为注销;

    <a href="<%=request.getContextPath()%>/pages/loginout.jsp">注销

    跳转到一个辅助页面loginout.jsp;

    该页面设置注销动作,并跳转到原页面:index.jsp

    session.invalidate();

    //使用重定向:

   response.sendRedirect(request.getContextPath()+"/index.jsp");

 

    PS:    

      1.超链接中设置的代码前 要加 =(等于号);

      2.通过该主动失效session,session的ID,也将失效,生成为新ID

(二)移除会话的属性

    public void removeAttribute(String name);

    用法:

       session.removeAttribute("username");

      与第一种主动失效编写一致,将方法由invalidate();改为removeAttribute("username");

     移除session中保存的属性,效果相同,但sessionID未失效。

   PS:session.invalidate();与removeAttribute("username"); 

     本质不同,前者是失效,后者是移除。

2.服务器设置session 的生命周期,多长时间没有请求自动清除。

(一) 设置回话过期时间

       1> public void setMaxlnactivelnterval(int interval);--单位:秒

       2>在项目中的Web.xml配置文件中添加属性标签。

        web.xml路径:在项目中WebRoot下文件夹WEB-INF下

 

        <session-config>

             <session-timeout>30</session-timeout>

        </session-config>

 

        PS:表示30分钟后失效,修改后,需要停止服务器,重新启动。

PS:教程中设置session过期在注册成功(设置setAttribute方法)代码之后进行编写,即:在注册成功即将跳转(sendRedirect方法)页面之前

 

例:<%

    if(username!=null && !username.equals("")){

        if(username.equals("admin")){

          //不允许注册,注册失败

         request.setAttribute("mess", "注册失败,请更换其他用户名");                   request.getRequestDispatcher("userCreate.jsp").forward(request, response);

        }else{

          //允许注册,注册成功

          session.setAttribute("username", username);  

          session.setMaxInactiveInterval(10);

          response.sendRedirect(request.getContextPath()+"/index.jsp");

          //换作用域保存,或者如下写法

        //response.sendRedirect(request.getContextPath()+"/index.jsp?info=success");

          //以上如果传递中文提示:

          /*String info = "注册成功!";

           info = URLEncoder.encode(info,"utf-8");

         response.sendRedirect(request.getContextPath()+"/index.jsp?info="+info);*/

        }

     %>

 <%}else{ 

     out.println("用户名未填写!");

   }%>

posted @ 2017-01-02 18:44  leer0  阅读(323)  评论(0)    收藏  举报