我的java历程

会话跟踪技术--session的使用

 

会话跟踪技术--session的使用

 

会话跟踪:

1、 使用隐藏表单字段

<INPUT TYPE=”HIDDEN” NAME=”session” VALUE=”landril”

2、 URL重写

http://host/path/file.jsp?sessionid=landril

3、 持久Cookie

4、 会话HttpSession

 

一、使用session的简单步骤

获取HttpSessionrequest.getSession()方法)对象,查找与该会话相关的信息(session.getAttribute()),存储会话中的信息(session.setAttribute()),删除会话中的数据(session.removeAttribute()),删除当前会话(session.invalidate()

session中,可以存储任意数量的键值对,通过键即可获取相应的值,即使用:session.getAttribute(“key”);

 

二、session的常用方法

1、 getAttribute():从session中获取以前存储的值

2、 getAttributeNames():返回session中所有属性的名称

3、 setAttribute():将键与值关联起来,存储进session

4、 removeAttribute():删除session中存储的对应键的值

5、 invalidate():删除整个session及其存储的键值

6、 logout():注销当前用户

7、 getId():获取每个session对应的唯一ID

8、 getCreationTime():获取session创建的时间

9、 getLastAccessedTime():获取session最后被访问的时间

10、              getMaxInactiveInterval():在用户没有访问的情况下,会话在被自动废弃之前应该保持多长时间

 

三、使用session的一个例子,拥有购物车的在线商店

 

1CatalogPage.java

 

package com.landril.session;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class CatalogPage extends HttpServlet {

 

    private CatalogItem[] items;

 

    private String[] itemIds;

 

    private String title;

 

    protected void setItems(String[] itemIds) {

       this.itemIds = itemIds;

       items = new CatalogItem[itemIds.length];

       for (int i = 0; i < items.length; i++) {

           items[i] = Catalog.getItem(itemIds[i]);

       }

    }

 

    protected void setTitle(String title) {

       this.title = title;

    }

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

      

       if(items == null){

           response.sendError(response.SC_NOT_FOUND,"Missing Items:");

           return;

       }

      

       response.setContentType("text/html");

       PrintWriter out = response.getWriter();

       out.println("<html><head><title>"+title+"</title></head><body><h3>"+title+"</h3>");

       CatalogItem item;

       for (int i = 0; i < items.length; i++) {

           out.println("<hr>");

           item = items[i];

           if(item == null)

              out.println("Unknow itemId: "+itemIds[i]);

           else{

              out.println();

              String formURL = request.getContextPath()+"/orderPage";

              formURL = response.encodeURL(formURL);

             

              out.println("<form action='"+formURL+"'>");

              out.println("<input type='hidden' name='itemId' value='"+item.getItemId()+"'>");

              out.println(new String(item.getSDesc().getBytes("utf-8"),"GBK")+"$"+item.getPrice()+item.getLDesc());

              out.println("<input type='submit' value='add to shopping cart'></form></body></html>");

           }

       }

    }

}

 

2ComputerBook.java

 

package com.landril.session;

 

public class ComputerBook extends CatalogPage{

    public void init(){

       String[] ids = {"book1","book2","book3","book4"};

       setItems(ids);

       setTitle("Japanese Book");

    }

}

 

3JapaneseBook.java

 

package com.landril.session;

 

public class JapaneseBook extends CatalogPage{

    public void init(){

       String[] ids = {"book5","book6"};

       setItems(ids);

       setTitle("Computer Book");

    }

}

 

4OrderPage.java

 

package com.landril.session;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

public class OrderPage extends HttpServlet {

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

       HttpSession session = request.getSession();

       ShoppingCart cart;

       synchronized(session){

           cart = (ShoppingCart)session.getAttribute("shop");

           if(cart == null){

              cart = new ShoppingCart();

              session.setAttribute("shop", cart);

           }

           String itemId = request.getParameter("itemId");

           if(itemId != null){

              String num = request.getParameter("num");

              if(num == null)

                  cart.addItem(itemId);

              else{

                  int numItems;

              try {

                  numItems = Integer.parseInt(num);

              } catch (NumberFormatException e) {

                  numItems = 1;

              }

              cart.setNum(itemId, numItems);

              }

           }

       }

      

       response.setContentType("text/html");

       PrintWriter out = response.getWriter();

       String title = "Your Order";

       out.println("<html><head><title>"+title+"</title></head><body><h3>"+title+"</h3>");

       synchronized(session){

           List<ItemOrder> itemOrders = cart.getItemOrders();

           if(itemOrders.size() == 0)

              out.println("No items");

           else{

              out.println("<table border=1><tr><th>Item ID<th>Short Description<th>Long Description<th>Unit Price<th>Number<th>Total Price");

              ItemOrder order;

              for (int i = 0; i < itemOrders.size(); i++) {

                  order = (ItemOrder)itemOrders.get(i);

                  out.println("<tr><td>"+order.getItemId()+"<td>"+order.getSDesc()+"<td>"+order.getLDesc()+"<td>"+order.getUnitPrice()+"<td>");

                  out.println("<form><input type='hidden' name='itemId' value='"+order.getItemId()+"'>");

                  out.println("<input type='text' name='num' size=3 value='"+order.getNum()+"'>");

                  out.println("<input type='submit' value='update order'></form><td>");

                  out.println(order.getTotalPrice());

               }

             

              String checkURL = response.encodeURL(request.getContextPath()+"/check.html");

              out.println("</table><form action='"+checkURL+"'>");

              out.println("<input type='submit' value='submit'></form></body></html>");

           }

       }

    }

}

 

5ShoppingCart.java

 

package com.landril.session;

 

import java.util.ArrayList;

import java.util.List;

 

public class ShoppingCart {

    private List<ItemOrder> itemOrders;

 

    public ShoppingCart() {

       itemOrders = new ArrayList<ItemOrder>();

    }

   

    public List<ItemOrder> getItemOrders(){

       return itemOrders;

    }

   

    public synchronized void addItem(String itemId){

       ItemOrder order;

       for(int i=0;i<itemOrders.size();i++){

           order = (ItemOrder)itemOrders.get(i);

           if(itemId.equals(order.getItemId())){

              order.addNum();

              return;

           }

       }

       ItemOrder newOrd = new ItemOrder(Catalog.getItem(itemId));

       itemOrders.add(newOrd);

    }

   

    public synchronized void setNum(String itemId,int num){

       ItemOrder order;

       for (int i = 0; i < itemOrders.size(); i++) {

           order = (ItemOrder)itemOrders.get(i);

           if(itemId.equals(order.getItemId())){

              if(num <=0)

                  itemOrders.remove(i);

              else

                  order.setNum(num);

           }

           return;

       }

       ItemOrder newOrd = new ItemOrder(Catalog.getItem(itemId));

       itemOrders.add(newOrd);

    }

}

 

6CatalogItem.java

 

package com.landril.session;

 

public class CatalogItem {

    private String itemId;

 

    private String sDesc;

 

    private String lDesc;

 

    private float price;

 

    public String getItemId() {

       return itemId;

    }

 

    public void setItemId(String itemId) {

       this.itemId = itemId;

    }

 

    public String getLDesc() {

       return lDesc;

    }

 

    public void setLDesc(String desc) {

       lDesc = desc;

    }

 

    public float getPrice() {

       return price;

    }

 

    public void setPrice(float price) {

       this.price = price;

    }

 

    public String getSDesc() {

       return sDesc;

    }

 

    public void setSDesc(String desc) {

       sDesc = desc;

    }

 

    public CatalogItem(String itemId, String desc, String desc2, float price) {

       super();

       this.itemId = itemId;

       sDesc = desc;

       lDesc = desc2;

       this.price = price;

    }

}

 

7ItemOrder.java

 

package com.landril.session;

 

public class ItemOrder {

    private CatalogItem item;

 

    private int num;

 

    public ItemOrder(CatalogItem item) {

       setItem(item);

       setNum(1);

    }

 

    public CatalogItem getItem() {

       return item;

    }

 

    public void setItem(CatalogItem item) {

       this.item = item;

    }

 

    public int getNum() {

       return num;

    }

 

    public void setNum(int num) {

       this.num = num;

    }

 

    public String getItemId() {

       return item.getItemId();

    }

 

    public String getSDesc() {

       return item.getSDesc();

    }

 

    public String getLDesc() {

       return item.getLDesc();

    }

 

    public float getUnitPrice() {

       return item.getPrice();

    }

 

    public void addNum() {

       setNum(num + 1);

    }

 

    public void cancelOrder() {

       setNum(0);

    }

 

    public float getTotalPrice() {

       return num * getUnitPrice();

    }

 

}

 

8Catalog.java

 

package com.landril.session;

 

public class Catalog {

    private static CatalogItem[] items = {

           new CatalogItem("book1", "Hibernate", "HibernateHibernate", 57),

           new CatalogItem("book2", "Spring", "SpringSpring", 36),

           new CatalogItem("book3", "Tomcat", "TomcatTomcat", 23),

           new CatalogItem("book4", "Jboss", "JbossJboss", 35),

           new CatalogItem("book5", "Japanese1", "Japanese1Japanese1", 35),

           new CatalogItem("book6", "Japanese2", "Japanese2Japanese2", 23) };

 

    public static CatalogItem getItem(String itemId) {

       CatalogItem item;

       if (itemId == null)

           return null;

       for (int i = 0; i < items.length; i++) {

           item = items[i];

           if (itemId.equals(item.getItemId()))

              return item;

       }

       return null;

    }

}

 

9check.html

 

<html>

<head>

<title>checking out</title>

</head>

<body>

Checking out

</body>

posted on 2007-04-28 21:33 landril 阅读(2635) 评论(1)  编辑  收藏 所属分类: Jsp&Servlet

Feedback

# re: 会话跟踪技术--session的使用 2008-07-14 22:30 宋雨

没有注释看不懂啊  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: