使用Cookie实现保存商品浏览记录

使用Cookie实现保存商品浏览记录

1.确定好框架

我新建了三个类。DBHelper.java来连接数据库,Items.java来封装数据,ItemsDAO.java来提供对Items的方法。

在页面显示上,我新建了俩个jsp。index.jsp来负责提供商品展示,detail.jsp来负责显示商品的细节(也就是模拟网上购物的情形,然后再detail.jsp上会显示你的浏览记录)

主要内容在最后!,题主只是为了把全部代码放上去罢了!,只是个例子参考! 初学者!

2.DBHelper.java

写数据库的,真的没什么好说的,直接上代码

package util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBHelper {
   
	private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
	private static final String url="jdbc:mysql://localhost:3306/shop"; //连接数据库的URL地址
	private static final String username="root"; //数据库的用户名
	private static final String password="123456"; //数据库的密码
    
	private static Connection conn=null;
	
	//静态代码块负责加载驱动
	static {
		try {
			Class.forName(driver);
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	//单例模式返回数据库连接对象
	public static Connection getConnection() throws Exception {
		if(conn==null) {
			conn = DriverManager.getConnection(url, username, password);
			return conn;
		}
		return conn;
	}
	
//	public static void main(String[] args) {
//
//		try {
//		   Connection conn = DBHelper.getConnection();
//		   if(conn!=null) {
//			   System.out.println("数据库连接正常!");
//		   }
//		   else {
//			   System.out.println("数据库连接异常!");
//		   }
//		} catch(Exception ex) {
//			ex.printStackTrace();
//		}
//	}
}

3.Items.java

这就是写一下变量,然后get、set,没啥好说了。其中get、set方法已经被我省略了。

package entity;

//商品类
public class Items {

	private int id; // 商品编号
	private String name; // 商品名称
	private String city; // 产地
	private int price; // 价格
	private int number; // 库存
	private String picture; // 商品图片
}

4.ItemsDAO.java

重点是gitViewList方法,这个是用来返回Cookie所存序号的内容。中规中矩的数据处理具体格式可以参考一下。

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import util.DBHelper;
import entity.Items;

//商品的业务逻辑类
public class ItemsDAO {

	// 获得所有的商品信息
	public ArrayList getAllItems() {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		ArrayList list = new ArrayList(); // 商品集合
		try {
			conn = DBHelper.getConnection();
			String sql = "select * from items;"; // SQL语句
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while (rs.next()) {
				Items item = new Items();
				item.setId(rs.getInt("id"));
				item.setName(rs.getString("name"));
				item.setCity(rs.getString("city"));
				item.setNumber(rs.getInt("number"));
				item.setPrice(rs.getInt("price"));
				item.setPicture(rs.getString("picture"));
				list.add(item);// 把一个商品加入集合
			}
			return list; // 返回集合。
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		} finally {
			// 释放数据集对象
			if (rs != null) {
				try {
					rs.close();
					rs = null;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			// 释放语句对象
			if (stmt != null) {
				try {
					stmt.close();
					stmt = null;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	// 根据商品编号获得商品资料
	public Items getItemsById(int id) {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			conn = DBHelper.getConnection();
			String sql = "select * from items where id=?;"; // SQL语句
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, id);
			rs = stmt.executeQuery();
			if (rs.next()) {
				Items item = new Items();
				item.setId(rs.getInt("id"));
				item.setName(rs.getString("name"));
				item.setCity(rs.getString("city"));
				item.setNumber(rs.getInt("number"));
				item.setPrice(rs.getInt("price"));
				item.setPicture(rs.getString("picture"));
				return item;
			} else {
				return null;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		} finally {
			// 释放数据集对象
			if (rs != null) {
				try {
					rs.close();
					rs = null;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			// 释放语句对象
			if (stmt != null) {
				try {
					stmt.close();
					stmt = null;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

		}
	}

	//获取最近浏览的前五条商品信息
	public ArrayList getViewList(String list)
	{
		System.out.println("list:"+list);
		ArrayList itemlist = new ArrayList();
		int iCount=5; //每次返回前五条记录
		if(list!=null&&list.length()>0) {
		    String[] arr = list.split(",");
		    System.out.println("arr.length="+arr.length);
		    //如果商品记录大于等于5条
		    if(arr.length>=iCount) {
		       for(int i=arr.length-1;i>=arr.length-iCount;i--)
		       {
		    	  itemlist.add(getItemsById(Integer.parseInt(arr[i])));  
		       }
		    }
		    else {
		    	for(int i=arr.length-1;i>=0;i--)
		    	{
		    		itemlist.add(getItemsById(Integer.parseInt(arr[i])));
		    	}
		    }
		    return itemlist;
		}
		else {
			return null;
		}
	}
}

5.index.jsp

这是jsp中用循环方式从数据库中调用数据显示在网页上,配合上上面一个ItemsDAO.java,很好理解的。

           
           <% 
               ItemsDAO itemsDao = new ItemsDAO(); 
               ArrayList list = itemsDao.getAllItems();
               if(list!=null&&list.size()>0)
               {
	               for(int i=0;i   
          
<%=item.getName() %>
产地:<%=item.getCity() %>  价格:¥ <%=item.getPrice() %>
<% } } %>

6.detail.jsp

              <% 
              String list ="";
              //从客户端获得Cookies集合
              Cookie[] cookies = request.getCookies();
              //遍历这个Cookies集合
              if(cookies!=null&&cookies.length>0)
              {
	              for(Cookie c:cookies)
	              {
	                  if(c.getName().equals("ListViewCookie"))
	                  {
	                     list = c.getValue();
	                  }
	              }
	          }
              
              list+=request.getParameter("id")+",";
              //如果浏览记录超过1000条,清零.
              String[] arr = list.split(",");
              if(arr!=null&&arr.length>0)
              {
                  if(arr.length>=1000)
                  {
                      list="";
                  }
              }
              Cookie cookie = new Cookie("ListViewCookie",list);
              response.addCookie(cookie);
          
          %>
          
          
             
您浏览过的商品
<% ArrayList itemlist = itemDao.getViewList(list); if(itemlist!=null&&itemlist.size()>0 ) { System.out.println("itemlist.size="+itemlist.size()); for(Items i:itemlist) { %>
<%=i.getName() %>
产地:<%=i.getCity() %>  价格:<%=i.getPrice() %> ¥
<% } } %>
不说了,到时候拿这个当模板去套吧~

你可能感兴趣的:(javaweb)