(5) session对象的使用

2016-09-09  本文已影响37人  笑笑学生

session对象常用方法:

序号 方法名 方法功能
1 getAttribute(String name) 获得指定名字的属性
2 getAttributeNames() 返回session对象中存储的每一个属性对象
3 getCreationTime() 返回session对象的创建时间
4 getId() 返回当前session对象的编号
5 getLastAccessedTime() 返回当前session对象最后一次被操作的时间
6 getMaxInactiveInterval() 获取session对象的生存时间
7 removeAttribute(String name) 删除指定属性的属性值和属性名
8 setAttribute(String name,Object obj) 设置指定名字的属性
9 Invalidate() 注销当前的session
10 isNew() 判断是否是一个新的session

核心代码
session.jsp

  <body>
    <%!
        int number =0;
        void countpeople(){
            number++;
        }
    %>
    <!--关闭浏览器不能累加  -->
    <%
        if(session.isNew()){
            countpeople();
        }
        String str = String.valueOf(number);
        session.setAttribute("count", str);
    %>
    <p>您是第<%=(String)session.getAttribute("count") %>个访问本站的人。</p>
    
    <!--记录表单信息 ,进行验证 -->
    <% String struser = request.getParameter("username"); %>
    <% String strpass = request.getParameter("password"); %>
    <%=struser %><br/>
    <%=strpass %><br/>
    <%
        if(struser==null)
            struser="";
        if(strpass==null)
            strpass="";
        if(struser.equals("xue") && strpass.equals("123")){
            out.println("登录成功");
            session.setAttribute("login", "OK");
            session.setAttribute("user",struser);
            session.setAttribute("pass",strpass);
            response.sendRedirect("welcome.jsp");
        }
        else{
            out.println("登录失败,5秒后,自动跳转到登陆界面");
            response.setHeader("Refresh", "5,URL=index.jsp");
        }
    %>
  </body>

welcome.jsp

  <body>
    <%
        String strLogin = (String)session.getAttribute("login");
        String strUser = (String)session.getAttribute("user");
        String strPass = (String)session.getAttribute("pass");
        if(strLogin == null){
            out.println("你好,请登录!5秒后,自动跳转到登陆界面");
            response.setHeader("Refresh", "5,URL=index.jsp");
        }
        else if(strLogin.equals("OK")){
            out.println(strUser+"欢迎进入我的网站");
        }else{
            out.println("登录出错,请重新登陆!");
        }
    %>
    
    <!-- application对象,使用请求转发,网址不变 -->
    <%
        application.setAttribute("user", strUser);
        application.setAttribute("pass", strPass);
    %>
    <form action="">
        <input type="submit" value="forward" name="forward"/>
    </form>
    <%
        String str = request.getParameter("forward");
        if(str==null)
            str="";
        //默认保存当前页面
        if(str.equals("forward")){
            response.sendRedirect("application.jsp");
        }
    %>
    <!-- 如何控制跳转? -->
    <%-- <jsp:forward page="application.jsp"></jsp:forward> --%>
  </body>
上一篇 下一篇

猜你喜欢

热点阅读