Chinaunix首页 | 论坛 | 博客
  • 博客访问: 627050
  • 博文数量: 125
  • 博客积分: 8703
  • 博客等级: 中将
  • 技术积分: 1102
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-10 17:48
文章分类

全部博文(125)

文章存档

2012年(2)

2011年(3)

2010年(11)

2009年(1)

2008年(12)

2007年(58)

2006年(38)

分类: Java

2006-03-14 17:29:09

动态页面和用户会话

      张彦星

1.创建动态的内容

动态网页的动态主要从以下几个方面获得:

  • 根据时间的动态;
  • 根据用户类型的动态;
  • 根据用户自定义信息的动态;
  • 根据用户来自的地区不一样的动态;
  • 根据数据库的内容动态;

1.1 根据时间的动态

dynamic_time.jsp

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>


 
    My JSP 'dynamic_time.jsp' starting page
   
 
  <% Date now = new Date();
       int month=now.getMonth();
       System.out.println(month);
       String bgcolor="";
         switch(month)
         {
             case(1):bgcolor="blue";break;
             case(2):bgcolor="eeccff";break;
             case(3):bgcolor="99cfdf";break;
             case(4):bgcolor="34ccff";break;
             case(5):bgcolor="4eccff";break;
             case(6):bgcolor="562342";break;
             case(7):bgcolor="dfe421";break;
             case(8):bgcolor="34ff00";break;
             case(9):bgcolor="yellow";break;
             case(10):bgcolor="green";break;
             case(11):bgcolor="9933ff";break;
             case(12):bgcolor="e40022";
         }
    %>
  >
   



    欢迎您?现在的时间是:<%=now.toLocaleString()%>
 

1.2 根据用户类型的动态

    系统中不同类型的用户,登录后产生的页面内容是不同。这种情况在工程项目管理方面的页面中非常常见。

     下面来看一个具体的例子。在案例项目中,至少存在两种用户,一个是普通用户,另一个是管理员。在用户登录后,把他们的用户类型信息保存在session中,这样在以后界面中就可以根据session中类型的不同生成不同的页面了。
title.jsp部分代码
if((Integer)session.getAtrribute("userType").equals(new Integer(1)))
   {
   %>
     个人信息
   <% }
    else
    {
    %>
   <%}%>
 
1.3 根据用户自定义信息的动态
    用户在注册时可以自定义一些信息,比如在在线书店的例子中,用户注册时可以选择喜欢的图书类型,那么用户登录时,就可以在登录后的界面中产生不同的链接。
 
例子(menu.jsp)片断
<%
    boolean isLog=false;
   try
   {
    isLog=((String)session.getAttribute("isLog")).equals("1");
   }
   catch(Exception e)
   {    
   }
   if(isLog){
    %>
  
             
            我的最好
         
    
    <%
     }
     %>
 
1.4 根据数据库的内容动态
    这种方式最常见的是把数据库中的内容读取出来,然后通过table显示在页面中。由于这种方式涉及到许多数据库编程的知识。
 
2.用户会话跟踪
 
2.1 会话跟踪的概念
   http是一种无状态的协议。也就是说,客户端在浏览服务器上的不同的页面时,每次请求获得响应完成后服务器和客户端的Scoket连接会关闭。但是在不同页面之间,我们往往需要交换信息。交换信息的方式有以下几种。
  • Http 信息:它将需要交换的信息保存在Http头部,随着代理服务器的出现和保密性的问题,这种技术早就过时了。
  • 隐藏字段:通过HTML的HIDDEN标记来传递信息:,这种方式存在保密性问题。
  • URL重写:把身份认证的信息加到页面链接的尾部,如:Next  改为:Next。这种方式同样存在安全的问题,同时,这个链接的长度还受URL长度的限制(一般URL长度最大为2K)
  • Cookie:浏览器把一些小的片断信息保存在客户端,在以后的使用过程中,服务器端可以使用客户端的Cookie。Cookie虽然是一个有效的解决方式,但是同样存在一些问题:客户端可以选择不接受Cookie,如果这样,有些程序可能不能正常运行。
  • session:session就是会话,简单地讲,会话可以定义在单一的用户和服务器之间定义一系列的交互,这些交互可以保持一段时间。一旦在服务器上建立一个会话,一个SessionId就和这个会话关联。一个客户端同时只有一个会话。
实例开发:
 
1. javaBean
  Item.java
 package com.starxing.ch6;

public class Item {
    private String itemId;//目录中商品的ID
    private float price;//商品价格
    private String description;//商品描述
    private boolean available;//商品是否有货
    private String producer;//商品厂商
    
    public Item(String itemId,String description,float price,
            boolean available,String producer)
    {
        this.itemId = itemId;
        this.price = price;
        this.description = description;
        this.available = available;
        this.producer = producer;
    }
    
    public String getItemId()
    {
        return itemId;
    }
    public float getPrice()
    {
        return price;
    }
    public String getDescription()
    {
        return description;
    }
    public boolean getAvailable()
    {
        return available;
    }
    public String getProducer()
    {
        return producer;
    }
    public void setItemId(String itemId)
    {
        this.itemId= itemId;
    }
    public void setPrice(float price)
    {
        this.price = price;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
    public void setAvailable(boolean available)
    {
        this.available = available;
    }
    public void setProducer(String producer)
    {
        this.producer = producer;
    }
}
Products.java
package com.starxing.ch6;

import java.util.Vector;

public class Products {
    private Vector items = new Vector();
   
   
    synchronized public Vector getItems() {
        return items;
    }
    synchronized public Item getItem(String itemId)
    {
        int index = Integer.parseInt(itemId);
        return (Item)items.elementAt(index);
    }
    synchronized public void setItem(Item item,String itemId)
    {
        int index = Integer.parseInt(itemId);
        items.set(index,item);
    }
    public Products()
    {
        items.addElement(new Item("0","JSP应用开发详解",(float)59,true,"电子工业出版社"));
        items.addElement(new Item("1","Java Web 服务开发",(float)45,true,"电子工业出版社"));
        items.addElement(new Item("2","Java 编程思想",(float)99,true,"机械工业出版社"));
        items.addElement(new Item("3","JSP 编程指南",(float)10,true,"电子工业出版社"));
        items.addElement(new Item("4","J2EE1.4应用开发详解",(float)68,true,"电子工业出版社"));
        items.addElement(new Item("5","J2EE企业级应用开发",(float)65,true,"电子工业出版社"));
        items.addElement(new Item("6","J2EE参考手册",(float)56,true,"电子工业出版社"));
        items.addElement(new Item("7","J2EE Web 服务开发",(float)55,true,"电子工业出版社"));
    }
    //商品的数量
    public int getSize()
    {
        return items.size();
    }
}
Cart.java
package com.starxing.ch6;

import java.util.HashMap;

public class Cart {
    private String userId;// 用户的标识

    private HashMap items;// 购物车中的物品

    public Cart() {
        items = new HashMap();
    }

    public void addItem(String itemId, int quantity) {
        items.put(itemId, new Integer(quantity));
    }

    public void removeItem(String itemId) {
        items.remove(itemId);
    }

    public void updateItem(String itemId, int quantity) {
        if (items.containsKey(itemId))
            items.remove(itemId);
        items.put(itemId, new Integer(quantity));
    }

    public HashMap getItems() {
        return this.items;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserId() {
        return this.userId;
    }

    public void clear() {
        items.clear();
    }
}
JSP
login.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<% session.invalidate() ;%>


Untitled Document








::请输入一个用户标识后点击登录::



 
   
 
 
   
 
 
   
 
 
   
 
用户登录
用户名:
用户名:






 checklogin.jsp
<%@ include file="/include.inc"%>
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page import="java.sql.DriverManager" %>




<% session.setMaxInactiveInterval(900);//设置session超时为30分种%>



 
 
   
    My JSP 'checklogin.jsp' starting page

   

 
 
 
    <%
       String id =request.getParameter("userId");
       String pwd = request.getParameter("password");
       Class.forName(CLASSFORNAME);
       Connection con = DriverManager.getConnection(SERVERNDDB,USER,PWD);
       Statement statement = con.createStatement();
       String isCorrect="select * from user_info where userId='" + id
                         + "' and password='"+pwd+"'" ;
       ResultSet result = statement.executeQuery(isCorrect);
      
       if(!result.next())
       {
          response.sendRedirect("login.jsp");
          result.close();
          statement.close();
          con.close();
       }
       else
       {
          session.setAttribute("name",result.getString("name"));
          session.setAttribute("id",result.getString("userId"));
          session.setAttribute("email",result.getString("email"));
          int count=result.getInt("userLogCount");
          session.setAttribute("userLogCount",new Integer(count));
          count++;
          session.setAttribute("userLastLogTime",result.getString("userLastLogTime"));
          java.util.Date time1 = new java.util.Date();
          String sqltime= new Timestamp(time1.getTime()).toString();
          statement.execute("update user_info set userLogCount=" + count
                            +",userLastLogTime='" + sqltime + "' where userId='"+id+"'");
          statement.close();
          con.close();
          //把页面派发到目的
          response.sendRedirect("shopping.jsp");
       }
    %>
 

shopping.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page import="com.starxing.ch6.*"%>




 
   
    My JSP 'shopping.jsp' starting page

   

 
 
 
    <%@ include file="/ch6/header.jsp" %>
   

   

   
      
        
        
        
        
        
      
     <%
        Vector v = products.getItems();
        Enumeration e = v.elements();
        while(e.hasMoreElements())
        {
          Item item = (Item)e.nextElement();
     %>
    
       
       
       
       
       
     
    
     <%
        }
     %>
  
    
    
    
id名称价格是否有库存出版社
<%=item.getDescription()%><%=item.getPrice()%><%=item.getAvailable()%><%=item.getProducer()%>
购物车『』注销

   

   

 

cart.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" import="com.starxing.ch6.*,java.util.*" pageEncoding="gb2312"%>







 
    My JSP 'cart.jsp' starting page
   
 
 
 
   <%
      //action 为执行的操作,add表示添加此商品,remove表示删除此商品
      String action=request.getParameter("action");
      //获得所有添加、删除的商品的itemed。
      String items[] = request.getParameterValues("itemId");
      if(items!=null)
      {
        for(int i=0;i
        {
           if(action.equals("add")) cart.addItem(items[i],1);
           else if(action.equals("remove")) cart.removeItem(items[i]);
        }
      }
   %>
   <%@ include file="header.jsp"%>
  

  

  
 
   
   
       
 
  <%
   HashMap cart_item=cart.getItems();
   Iterator it=cart_item.keySet().iterator();
 
   while(it.hasNext())
    {
     String itemId=(String)it.next();
     Item item=products.getItem(itemId);
        
    %>
  
      
   
        
 
  <%}%>
 
 
 
id名称数量
<%=item.getDescription()%><%=cart_item.get(itemId)%>
购物『』注销

  

  

 

logout.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>



 
    My JSP 'logout.jsp' starting page
 
 
 
   <%
     cart.clear();
     session.invalidate();
     response.sendRedirect("login.jsp");
   %>
 

header.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>



 
    My JSP 'logout.jsp' starting page
 
 
 
   <%
     cart.clear();
     session.invalidate();
     response.sendRedirect("login.jsp");
   %>
 


阅读(2022) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~