java web 学习 --第六天(Java三级考试)

第五天学习在这:http://www.cnblogs.com/tobecrazy/p/3458592.html

session对象

 

当某个用户首次访问web应用系统时,jsp会自动创建出一个session对象,同时为它分配一个字符串String类型的唯一标识符ID值,该值为会话ID也称为session ID 。jsp会将这个ID 发送带客户端浏览器中,浏览器在将它保存在cookie中,而session本身的数据保存在服务器端,但是标识session ID的数据却能保存在客户机cookie

 

Session方法:

  •   getAttribute(String name) 获取指定名字的属性值,若不存在,返回null

 

  •   setAttribute(String name,object value ) 设置指定名字的属性值,并将其存储在session对象中

 

  •   removeAttribute(String name) 删除指定属性(包括属性名、属性值)

 

  •   getAttributeNames() 返回session对象中存储的第一个属性对象,结果集是一个Enumeration

 

  •   getCreateTime() 返回session对象创建的时间,以毫秒计算

 

  •   getId() 没生成一个session对象,服务器都会给其一个不重复的编号,返回当前session对象的ID

 

  •   getLastAccessedTime() 返回session对象最后一次操作的时间,以毫秒计算

 

  •   getMaxInpactiveInterval() 获得session对象生存时间

 

  •   setMaxInpactiveInterval(int interval) 设置session对象的有效时间单位秒 ,也可以设置在 web.xml配置文件中

 

jsp 规范推荐采用getAttribute()方法代替getValue()方法

 

Session对象的主要作用: 为HTTP会话提供控制各种方法,可以存储在会话过程中所产生的各种结果数据,做为一个数据缓存器使用。因此在web项目中,可以使用session对象跟踪用户在线状态和保存用户请求的各种特征数据也可以用以识别用户身份类型、识别是否在线和系统中在线用户总数。

实例使用session对象,实现用户身份识别:

还是使用昨天的登录页面:

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page isErrorPage="true" errorPage="error.jsp"  %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>login.jsp</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
 
  
   <form method="post" action="response.jsp"> 
   username: 
   <input type="text" name="username" > 
   <br>
   password:
   <input type="password" name="password">
   <br>
   userType:
   <select name="userType">
   <option value="user" >user</option>
   <option value="master"> master</option>
   </select>
   
   <input type="submit" name="submit" />
   </form>
 
    
  </body>
</html>
View Code

对于登录action的response页面,登录成功,能看到权限内容

登录失败,forward到login.jsp

首先添加一个UserInfo类,设置三个属性,并添加get/set方法和一个验证数据的方法

package mypackage;

public class UserInfo {

    /**
     * @param args
     * two parameters add get/set methods
    */
    
    String userName=null;
    String passWord=null;
    String userType=null;
    public String getUserType() {
        return userType;
    }
    public void setUserType(String userType) {
        this.userType = userType;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    
    public boolean  verifyID( )  //如果用户名是young并且密码是1234返回true
    {
        if(userName.equals("young") && passWord.equals("1234"))
        {
             System.out.print("login successful\n");
             return true;
        }
        else
        {
            System.out.print("login failure\n");
            return false;
        }
        
    }
    
}

response.jsp页面,登录成功直接跳转至welcome.jsp登录失败跳转到error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page  contentType="text/html;charset=gbk" %>
<jsp:useBean id="login" class="mypackage.UserInfo" scope="page"></jsp:useBean> <!-- 引入UerInfo类-->
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>response login.jsp</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
  <%!
      String targetPage=null;
      RequestDispatcher rd=null;
   %>
    <%  
   login.setUserName(request.getParameter("username")); 
   login.setPassWord(request.getParameter("password"));
   login.setUserType(request.getParameter("userType"));
 
   login.verifyID();
    
    if(login.verifyID() )
   {
          out.print("登录成功,欢迎"+request.getParameter("userType") + login.getUserName());
          //out.print(request.getCookies().toString() +request.getSession());
          targetPage="welcome.jsp";
          request.setAttribute("userNameString",login.getUserName());
          session.setAttribute("UserInfoVO",login);//登录成功保存用户基本信息在session对象中
                   
   } 
   else
   {
   
          request.setAttribute("errorMSG","登录失败,用户名或密码错误");
            targetPage="error.jsp";
          session.setAttribute("UserInfoVO",null);//登录失败 销毁对象保存在session
   } 
   rd=request.getRequestDispatcher(targetPage);
   rd.forward(request,response);
   %>
  </body>
</html>

welcome页面,先判断用户是否登录,从session中到相应的类,如果是null,显示登录失败,forward登录页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="mypackage.*" %>
  <% UserInfo user1=(UserInfo) session.getAttribute("UserInfoVO");
  if(user1==null)
  {
            request.setAttribute("errorMSG","你没有登录,请登录");
            String  targetPage="login.jsp";
            RequestDispatcher rd=request.getRequestDispatcher(targetPage);
            rd.forward(request,response); //未登录跳转到login.jsp
              }
  %>
    
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'welcome.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body> 
 welcome <%=user1.getUserName() %><br>
 your userType is <%=user1.getUserType() %> <br>


  </body>
</html>

error.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.sql.*" %> 
<%@page import="java.sql.Connection"  %>
<%@page import="java.sql.DriverManager"  %>
<%@page import ="java.sql.ResultSet"  %>
<%@page import ="java.sql.Statement"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    
    <title>permission denied JSP page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>  
  <h1>permission denied to access this page,please login </h1>
  
     <br>
    
  </body>
</html>
View Code

 

控制会话声明期

通过修改web.xml文件

或者在web.xml直接添加:

<session-config>

  <session-timeout>1</session-timeout>

 </session-config>

此外还可以通过HttpSession接口中的setMaxInactiveInterval()方法设置,单位秒

 

posted @ 2013-12-06 22:44  to be crazy  阅读(578)  评论(0编辑  收藏  举报