.会话管理之Cookie案例二:显示已浏览商品

来源:互联网 发布:陆金所网络投融资平台 编辑:程序博客网 时间:2024/05/21 09:43

项目开发步骤:数据库——>创键实体对象entity——>创建数据访问dao——>创建servlet

第一步:创建数据库:这里使用的xml文件创建数据库,内容如下:

<?xml version="1.0" encoding="utf-8"?><product-list><product id="1"><name>联想笔记本</name><type>LN001</type><price>5000</price></product><product id="2"><name>长城笔记本</name><type>CN001</type><price>3000</price></product><product id="3"><name>惠普笔记本</name><type>HP001</type><price>2000</price></product><product id="4"><name>戴尔笔记本</name><type>DL001</type><price>6000</price></product><product id="5"><name>神州笔记本</name><type>SZ001</type><price>900</price></product></product-list>

第二步:创建实体对象:

public class Product {private String id;private String name;private String type;private String price;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}}


第三步:创建数据访问类,包含对数据的增删改查

首先创建对xml文件解析的类,导入相关jar包

public class XMLUtil {/** * 读取xml文件,返回document对象 */public static Document getDocument(){try {Document doc = new SAXReader().read(new File("e:/product.xml"));return doc;} catch (DocumentException e) {e.printStackTrace();//把转换为运行时异常抛出即可!throw new RuntimeException(e);}}/** * 传如docuemnt对象,写出到xml文件中 */public static void write2xml(Document doc){try {OutputStream out = new FileOutputStream("e:/product.xml");OutputFormat format = OutputFormat.createPrettyPrint();XMLWriter writer = new XMLWriter(out,format);writer.write(doc);writer.close();} catch (Exception e) {e.printStackTrace();//把转换为运行时异常抛出即可!throw new RuntimeException(e);}}}
在对xml文件解析的基础上创建对数据库增删改查的方法:

public class ProductDao {//查找所有商品public List<Product> findAll() {//读取xml文件Document doc = XMLUtil.getDocument();//读取所有的Product标签List<Element> elements = doc.getRootElement().elements("product");List<Product> list = new ArrayList<Product>();//遍历所有的Product标签for(Element ele:elements){//创建Product对象,并将product内容封装到对象中Product p = new Product();p.setId(ele.attributeValue("id"));p.setName(ele.elementText("name"));p.setType(ele.elementText("type"));p.setPrice(ele.elementText("price"));//将封装好的对象添加到集合中list.add(p);}//将集合返回return list;}//根据id查找商品详细信息public Product findById(String id){//获取xml文件Document doc = XMLUtil.getDocument();//查询指定id的product标签Element proelem = (Element)doc.selectSingleNode("//product[@id='"+id+"']");//创建Product对象Product p =null;// 如果找到指定id的product标签if(proelem!=null){p = new Product();//通过找到的product标签找到product的对象属性,并将其封装。p.setId(proelem.attributeValue("id"));p.setName(proelem.elementText("name"));p.setType(proelem.elementText("type"));p.setPrice(proelem.elementText("price"));}return p;}public static void main(String[] args) {/* * 用于测试上面的方法是否正确 */ProductDao dao = new ProductDao();/*List<Product> list = dao.findAll();for(Product pro:list){System.out.println(pro.getName());}*/Product p = dao.findById("2");System.out.println(p.getName());}}

第四步:创建servlet,这里包含两个servlet, 一个用于商品列表展示,一个用于显示详细信息和保存cookie.

商品列表展示servlet:

 

public class ListProdServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//读取到所有商品的列表ProductDao prodao = new ProductDao();List<Product> list = prodao.findAll();//把商品显示到浏览器response.setContentType("text/html;charset=utf-8");String html = "";html += "<html>";html += "<head><title>查看商品列表</title></head>";html += "<body>";html += "<table border='1' align='center' width='600px'>";html += "<tr><th>编号</th><th>商品名称</th><th>商品型号</th><th>价格</th><th>查看详情</th></tr>";//遍历所有商品,有几个商品就有几行数据if(list!=null){for(Product pro:list){html+="<tr>";html+="<td>"+pro.getId()+"</td>";html+="<td>"+pro.getName()+"</td>";html+="<td>"+pro.getType()+"</td>";html+="<td>"+pro.getPrice()+"</td>";html+="<td><a href='"+request.getContextPath()+"/DetailProdServlet?id="+pro.getId()+"'>查看</a></td>";html+="</tr>";}}html+="</table>";//显示浏览过的商品html +="<hr/>";html +="最近浏览过的商品<br/>";Cookie[] cookies = request.getCookies();if(cookies!=null){for (Cookie cook : cookies) {if(cook.getName().equals("prodHist")){String prodHist = cook.getValue();String[] ids = prodHist.split(",");for (String id : ids) {Product p =  prodao.findById(id);//将商品信息显示出来html+=""+p.getId()+" "+p.getName()+" "+p.getPrice()+"<br/>";}break;}}}html += "</body>";html += "</html>";response.getWriter().write(html);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

显示详细信息的servlet:

public class DetailProdServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String id = request.getParameter("id");ProductDao pdao = new ProductDao();Product pro = pdao.findById(id);//将商品信息展示在浏览器上response.setContentType("text/html;charset=utf-8");String html = "";html += "<html>";html += "<head><title>查看商品详情</title></head>";html += "<body>";html += "<table border='1' align='center' width='250px'>";html += "<tr><th>商品编号</th><td>"+pro.getId()+"</td></tr>";html += "<tr><th>商品名称</th><td>"+pro.getName()+"</td></tr>";html += "<tr><th>商品类型</th><td>"+pro.getType()+"</td></tr>";html += "<tr><th>商品价格</th><td>"+pro.getPrice()+"</td></tr>";html += "</table>";html += "<center><a href='"+request.getContextPath()+"/ListProdServlet'>[返回商品列表]</a></center>";html += "</body>";html += "</html>";response.getWriter().write(html);//创建cookie保存浏览过的商品编号Cookie c = new Cookie("prodHist", getCookieValue(request,pro.getId()));response.addCookie(c);}/* *  *   规则:  *     1)不能超过3个,最多3个 *     2)最后访问的商品放在最前面 *      * 该方法返回最终生成的浏览过的商品的编号列表 * 现在的值           传入的id值          最终的值          算法 *     null或没有prodHist        1                  1              直接返回传入的id    *         2,1                   1                  1,2        小于3个,且id有重复的: 删除重复的id,把传入的id放前面 *         2,1                   3                  3,2,1   小于3个,且id没有重复的:直接把传入的id放前面 *         3,2,1                 2                  2,3,1   等于3个,且id有重复的: 删除重复的id,把传入的id放前面 *         3,2,1                 4                  4,3,2   等于3个,且id没有重复的:    删除结尾的id,把传入的id放前面                      *        */private String getCookieValue(HttpServletRequest request,String id) { Cookie[] cookies = request.getCookies(); String prodHist=null; //将cookie信息放入一个prodHist中, if(cookies!=null){ for(Cookie cook:cookies){ if(cook.getName().equals("prodHist")){ prodHist= cook.getValue();break; } } } //如果是第一次写入,则直接返回id if(cookies==null||prodHist==null){ return id; }// 满足两个条件:1)方便判断元素是否重复  2)方便增删元素内容        使用集合: Collection   coll.contains(id): 判断指定元素是否存在    //     List: ArrayList LinkedList(链表),这里使用linkedList比较适合  //先将prodHist中保存的字符串变成数组 String[] prodHists = prodHist.split(","); //将String[]变成Collection集合Collection coll =  Arrays.asList(prodHists); //将Collection集合转换为LinkedListLinkedList list = new LinkedList(coll);if(list.size()<3){//如果已经有了这个idif(list.contains(id)){//删除重复的idlist.remove(id);list.addFirst(id);}else {list.addFirst(id);}}else {//有重复的,删除重复的,把传入的id放在前面if(list.contains(id)){list.remove(id);list.addFirst(id);}else {//没有重复的,删除最后一个id,将传入的id放前面list.removeLast();list.addFirst(id);}}//list集合变成String字符串String str="";for (Object obj : list) {str+=obj+",";}//去掉最后的逗号str = str.substring(0,str.length()-1);return str;}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

重点是对浏览过的商品列表的排序,需要使用LinkedList集合,如果使用数组,则需要多次的复制和转移,相当麻烦。




0 0
原创粉丝点击