zoukankan      html  css  js  c++  java
  • JAVA遇见HTML——Servlet篇:应用MVC架构实现项目

    java关键字“this”只能用在方法方法体内。当一个对象创建之后,java虚拟机就会给这个对象分配一个引用自身的指针,这个指针的名字就是this。只能在非静态方法中使用

      1 package servlet;
      2 
      3 import java.io.IOException;
      4 import java.io.PrintWriter;
      5 
      6 import javax.servlet.ServletException;
      7 import javax.servlet.http.HttpServlet;
      8 import javax.servlet.http.HttpServletRequest;
      9 import javax.servlet.http.HttpServletResponse;
     10 
     11 public class GetInitParameterServlet extends HttpServlet {
     12     
     13     private String username;//用户名
     14     private String password;//密码
     15     
     16     public String getUsername() {
     17         return username;
     18     }
     19 
     20     public void setUsername(String username) {
     21         this.username = username;
     22     }
     23 
     24     public String getPassword() {
     25         return password;
     26     }
     27 
     28     public void setPassword(String password) {
     29         this.password = password;
     30     }
     31 
     32     /**
     33      * Constructor of the object.
     34      */
     35     public GetInitParameterServlet() {
     36         super();
     37     }
     38 
     39     /**
     40      * Destruction of the servlet. <br>
     41      */
     42     public void destroy() {
     43         super.destroy(); // Just puts "destroy" string in log
     44         // Put your code here
     45     }
     46 
     47     /**
     48      * The doGet method of the servlet. <br>
     49      *
     50      * This method is called when a form has its tag value method equals to get.
     51      * 
     52      * @param request the request send by the client to the server
     53      * @param response the response send by the server to the client
     54      * @throws ServletException if an error occurred
     55      * @throws IOException if an error occurred
     56      */
     57     public void doGet(HttpServletRequest request, HttpServletResponse response)
     58             throws ServletException, IOException {
     59 
     60         doPost(request,response);
     61     }
     62 
     63     /**
     64      * The doPost method of the servlet. <br>
     65      *
     66      * This method is called when a form has its tag value method equals to post.
     67      * 
     68      * @param request the request send by the client to the server
     69      * @param response the response send by the server to the client
     70      * @throws ServletException if an error occurred
     71      * @throws IOException if an error occurred
     72      */
     73     public void doPost(HttpServletRequest request, HttpServletResponse response)
     74             throws ServletException, IOException {
     75 
     76         response.setContentType("text/html;charset=utf-8");
     77         PrintWriter out = response.getWriter();
     78         out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
     79         out.println("<HTML>");
     80         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
     81         out.println("  <BODY>");
     82         out.print("    This is ");
     83         out.print(this.getClass());
     84         out.println(", using the POST method");
     85         out.println("<h2>"+"用户名:"+this.getUsername()+"</h2>");
     86         out.println("<h2>"+"密码:"+this.getPassword()+"</h2>");
     87         out.println("  </BODY>");
     88         out.println("</HTML>");
     89         out.flush();
     90         out.close();
     91     }
     92 
     93     /**
     94      * Initialization of the servlet. <br>
     95      *
     96      * @throws ServletException if an error occurs
     97      */
     98     public void init() throws ServletException {
     99         // Put your code here
    100         this.setUsername(this.getInitParameter("username"));
    101         this.setPassword(this.getInitParameter("password"));
    102     }
    103 
    104 }

    web.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="2.5" 
     3     xmlns="http://java.sun.com/xml/ns/javaee" 
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     7   <display-name></display-name>
     8   <servlet>
     9     <description>This is the description of my J2EE component</description>
    10     <display-name>This is the display name of my J2EE component</display-name>
    11     <servlet-name>GetInitParameterServlet</servlet-name>
    12     <servlet-class>servlet.GetInitParameterServlet</servlet-class>
    13       <init-param>
    14       <param-name>username</param-name>
    15       <param-value>admin</param-value>
    16       </init-param>
    17       <init-param>
    18       <param-name>password</param-name>
    19       <param-value>123456</param-value>
    20       </init-param>
    21   </servlet>
    22 
    23   <servlet-mapping>
    24     <servlet-name>GetInitParameterServlet</servlet-name>
    25     <url-pattern>/servlet/GetInitParameterServlet</url-pattern>
    26   </servlet-mapping>    
    27   <welcome-file-list>
    28     <welcome-file>index.jsp</welcome-file>
    29   </welcome-file-list>
    30 </web-app>
     1 <%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>获取初始化参数演示案例</h1>
    25     <hr>
    26     <a href="servlet/GetInitParameterServlet">获取初始化参数servlet</a>
    27   </body>
    28 </html>

    设计类的时候主要考虑两方面因素:设计这个类的属性和方法

    entity:实体层

    集合类型:序列、set、hashset

    购买商品的集合:用Map类型表示购买商品的集合,键:商品对象,值:商品购买的数量

    键:Items商品类型,值:Integer购买的数量

    代码实现:

     1 package entity;
     2 
     3 import java.util.HashMap;
     4 import java.util.Iterator;
     5 import java.util.Map;
     6 import java.util.Set;
     7 
     8 //购物车类
     9 public class Cart {
    10     //购买商品的集合
    11     private HashMap<Items,Integer> goods;
    12     //购物车的总金额
    13     private double totalPrice;
    14     //构造方法
    15     public Cart() {
    16         //初始化属性
    17         goods = new HashMap<Items,Integer>();
    18         totalPrice=0.0;
    19     }
    20     public HashMap<Items, Integer> getGoods() {
    21         return goods;
    22     }
    23     public void setGoods(HashMap<Items, Integer> goods) {
    24         this.goods = goods;
    25     }
    26     public double getTotalPrice() {
    27         return totalPrice;
    28     }
    29     public void setTotalPrice(double totalPrice) {
    30         this.totalPrice = totalPrice;
    31     }
    32     
    33     //添加商品进购物车的方法
    34     public boolean addGoodsInCart(Items item,int number)//参数:商品对象item,商品数量number
    35     {//判断购物车是否包含该商品
    36         if(goods.containsKey(item))//如果此映射包含对于指定键的映射关系,则返回 true。
    37         {
    38             goods.put(item, goods.get(item)+number);//在此映射中关联指定值与指定键。
    39         }
    40         else{//第一次购买这个商品
    41             goods.put(item, number);
    42         }
    43         //当你添加和删除商品之后,都应该重新计算购物车的总金额
    44         calTotalPrice();//重新计算购物车的总金额
    45         return true;
    46     }
    47     
    48     //删除商品的方法
    49     public boolean removeGoodsFromCart(Items item)
    50     {
    51         goods.remove(item);//从此映射中移除指定键的映射关系(如果存在)。
    52         calTotalPrice();//重新计算购物车的总金额
    53         return true;
    54     }
    55     
    56     //统计购物车的总金额
    57     public double calTotalPrice(){
    58         
    59         double sum=0.0;
    60         //遍历Map类型的集合
    61         Set<Items> keys=goods.keySet();//获得键的集合
    62         //set类型用for循环是没法遍历的,必须使用迭代器
    63         Iterator<Items> it=keys.iterator();//获得迭代器对象
    64         //Iterator用while遍历
    65         while(it.hasNext()){
    66             //遍历商品对象
    67             Items i=it.next();
    68             //计算总价格:单价*购买数量
    69             sum+=i.getPrice()*goods.get(i);//调用get方法取得每个键对应的value
    70             }
    71         this.setTotalPrice(sum);//设置购物车的总金额
    72         return this.getTotalPrice();//返回总金额
    73         }
    74     public static void main(String[] args){
    75         //先创建两个商品对象
    76         Items i1 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg");
    77         Items i2 = new Items(2,"李宁运动鞋","广州",300,500,"002.jpg");
    78         Items i3 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg");
    79     
    80         Cart c = new Cart();
    81         c.addGoodsInCart(i1, 1);
    82         c.addGoodsInCart(i2, 2);
    83         //再次购买沃特篮球鞋,购买3双
    84         c.addGoodsInCart(i3, 3);
    85         
    86         // 通过entrySet方法,返回Map中的所有键值对
    87         //遍历购物商品的集合
    88         Set<Map.Entry<Items, Integer>> items= c.getGoods().entrySet();//Entry<Items, Integer>键值对对象
    89         for(Map.Entry<Items, Integer> obj:items)
    90         {
    91             System.out.println(obj);
    92         }
    93         
    94         
    95         System.out.println("购物车的总金额:"+c.getTotalPrice());
    96     }
    97 
    98 }

    重写Items类中的两个方法:equals(Object),hashCode()

     

     1     //改写hashCode生成规则
     2     @Override
     3     public int hashCode() {//hashCode是这个对象的哈希码
     4         // TODO Auto-generated method stub
     5         return this.getId()+this.getName().hashCode();//商品的编号、商品的名称如果这两个都相同,那生成的hashCode也相同(相同的字符串,hashCode也相同)
     6     }
     7 
     8     //判断这两个对象的内容是否相同 
     9     @Override
    10     public boolean equals(Object obj) {
    11         // 如果当前对象就等于传进来的对象,则这是两个相同的对象
    12         if(this==obj){
    13             return true;
    14         }
    15         
    16         //判断是否属于商品类
    17         if(obj instanceof Items){//使用 instanceof 判断一个实例是否属于某种类型
    18             Items i=(Items)obj;
    19             //判断商品编号和商品名称都和当前商品完全一样的话,要比较的商品对象和我自身的这个对象它的内容是相同的
    20             if(this.getId()==i.getId()&&this.getName().equals(i.getName())){
    21                 return true;
    22             }
    23             else
    24             {
    25                 return false;
    26             }
    27         }
    28         else{
    29             return false;
    30         }
    31     }

    编写Servlet:添加商品进购物车

    path是项目的根目录,服务器的根目录:WebRoot

    代码实现:

      1 package servlet;
      2 
      3 import java.io.IOException;
      4 import java.io.PrintWriter;
      5 
      6 import javax.servlet.ServletException;
      7 import javax.servlet.http.HttpServlet;
      8 import javax.servlet.http.HttpServletRequest;
      9 import javax.servlet.http.HttpServletResponse;
     10 
     11 import dao.ItemsDAO;
     12 import entity.Cart;
     13 import entity.Items;
     14 
     15 public class CartServlet extends HttpServlet {
     16 
     17     private String action ; //表示购物车的动作 ,add,show,delete
     18     //商品业务逻辑类的对象
     19     private ItemsDAO idao = new ItemsDAO();
     20     
     21     
     22     /**
     23      * Constructor of the object.
     24      */
     25     public CartServlet() {
     26         super();
     27     }
     28 
     29     /**
     30      * Destruction of the servlet. <br>
     31      */
     32     public void destroy() {
     33         super.destroy(); // Just puts "destroy" string in log
     34         // Put your code here
     35     }
     36 
     37     /**
     38      * The doGet method of the servlet. <br>
     39      *
     40      * This method is called when a form has its tag value method equals to get.
     41      * 
     42      * @param request the request send by the client to the server
     43      * @param response the response send by the server to the client
     44      * @throws ServletException if an error occurred
     45      * @throws IOException if an error occurred
     46      */
     47     public void doGet(HttpServletRequest request, HttpServletResponse response)
     48             throws ServletException, IOException {
     49         doPost(request,response);
     50     }
     51 
     52     /**
     53      * The doPost method of the servlet. <br>
     54      *
     55      * This method is called when a form has its tag value method equals to post.
     56      * 
     57      * @param request the request send by the client to the server
     58      * @param response the response send by the server to the client
     59      * @throws ServletException if an error occurred
     60      * @throws IOException if an error occurred
     61      */
     62     public void doPost(HttpServletRequest request, HttpServletResponse response)
     63             throws ServletException, IOException {
     64 
     65         response.setContentType("text/html;charset=utf-8");
     66         PrintWriter out = response.getWriter();
     67         if(request.getParameter("action")!=null)
     68         {
     69             this.action = request.getParameter("action");
     70             if(action.equals("add")) //如果是添加商品进购物车
     71             {
     72                 if(addToCart(request,response))
     73                 {
     74                     request.getRequestDispatcher("/success.jsp").forward(request, response);
     75                 }
     76                 else
     77                 {
     78                     request.getRequestDispatcher("/failure.jsp").forward(request, response);
     79                 }
     80             }
     81             if(action.equals("show"))//如果是显示购物车
     82             {
     83                 request.getRequestDispatcher("/cart.jsp").forward(request, response);
     84             }
     85             if(action.equals("delete")) //如果是执行删除购物车中的商品
     86             {
     87                 if(deleteFromCart(request,response))
     88                 {
     89                     request.getRequestDispatcher("/cart.jsp").forward(request, response);
     90                 }
     91                 else
     92                 {
     93                     request.getRequestDispatcher("/cart.jsp").forward(request, response);
     94                 }
     95             }
     96         }
     97         
     98     }
     99 
    100     //添加商品进购物车的方法
    101     private boolean addToCart(HttpServletRequest request, HttpServletResponse response)
    102     {//商品id
    103         String id = request.getParameter("id");
    104         //商品数量
    105         String number = request.getParameter("num");
    106         //商品资料
    107         Items item = idao.getItemsById(Integer.parseInt(id));//Integer.parseInt(id)转换成整型
    108         
    109         //是否是第一次给购物车添加商品,需要给session中创建一个新的购物车对象
    110         if(request.getSession().getAttribute("cart")==null)
    111         {
    112             Cart cart = new Cart();
    113             //填到session当中
    114             request.getSession().setAttribute("cart",cart);
    115         }
    116         //获得session对象
    117         Cart cart = (Cart)request.getSession().getAttribute("cart");
    118         if(cart.addGoodsInCart(item, Integer.parseInt(number)))//Integer.parseInt(number)字符串类型强转成int类型
    119         {
    120             return true;
    121         }
    122         else
    123         {
    124             return false;
    125         }
    126         
    127     }
    128     
    129     //从购物车中删除商品
    130     private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response)
    131     {
    132         String id = request.getParameter("id");
    133         Cart cart = (Cart)request.getSession().getAttribute("cart");
    134         Items item = idao.getItemsById(Integer.parseInt(id));
    135         if(cart.removeGoodsFromCart(item))
    136         {
    137             return true;
    138         }
    139         else
    140         {
    141             return false;
    142         }
    143     }
    144     
    145     /**
    146      * Initialization of the servlet. <br>
    147      *
    148      * @throws ServletException if an error occurs
    149      */
    150     public void init() throws ServletException {
    151         // Put your code here
    152     }
    153 
    154 }

    detail.jsp

      1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
      2 <%@ page import="entity.Items"%>
      3 <%@ page import="dao.ItemsDAO"%>
      4 <%
      5 String path = request.getContextPath();
      6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      7 %>
      8 
      9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     10 <html>
     11   <head>
     12     <base href="<%=basePath%>">
     13     
     14     <title>My JSP 'details.jsp' starting page</title>
     15     
     16     <meta http-equiv="pragma" content="no-cache">
     17     <meta http-equiv="cache-control" content="no-cache">
     18     <meta http-equiv="expires" content="0">    
     19     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     20     <meta http-equiv="description" content="This is my page">
     21     <!--
     22     <link rel="stylesheet" type="text/css" href="styles.css">
     23     -->
     24     <link href="css/main.css" rel="stylesheet" type="text/css">
     25     <script type="text/javascript" src="js/lhgcore.js"></script>
     26     <script type="text/javascript" src="js/lhgdialog.js"></script>
     27     <script type="text/javascript">
     28       function selflog_show(id)//id要购买的商品编号 ,num购买商品数量,&action=add添加商品进购物车,path是项目的根目录,服务器的根目录:WebRoot
     29       { 
     30          var num =  document.getElementById("number").value; 
     31          J.dialog.get({id: 'haoyue_creat',title: '购物成功', 600,height:400, link: '<%=path%>/servlet/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
     32       }
     33       function add()
     34       {
     35          var num = parseInt(document.getElementById("number").value);
     36          if(num<100)
     37          {
     38             document.getElementById("number").value = ++num;
     39          }
     40       }
     41       function sub()
     42       {
     43          var num = parseInt(document.getElementById("number").value);
     44          if(num>1)
     45          {
     46             document.getElementById("number").value = --num;
     47          }
     48       }
     49      
     50     </script>
     51     
     52     <style type="text/css">
     53        hr{
     54          
     55          border-color:FF7F00; 
     56        }
     57        
     58        div{
     59           float:left;
     60           margin-left: 30px;
     61           margin-right:30px;
     62           margin-top: 5px;
     63           margin-bottom: 5px;
     64          
     65        }
     66        div dd{
     67           margin:0px;
     68           font-size:10pt;
     69        }
     70        div dd.dd_name
     71        {
     72           color:blue;
     73        }
     74        div dd.dd_city
     75        {
     76           color:#000;
     77        }
     78        div #cart
     79        {
     80          margin:0px auto;
     81          text-align:right; 
     82        }
     83        span{
     84          padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer;
     85        }
     86        a{
     87           text-decoration: none; 
     88        }
     89     </style>
     90   </head>
     91   
     92   <body>
     93     <h1>商品详情</h1>
     94     <a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
     95     <hr>
     96     <center>
     97       <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
     98         <tr>
     99           <!-- 商品详情 -->
    100           <% 
    101              ItemsDAO itemDao = new ItemsDAO();
    102              Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
    103              if(item!=null)
    104              {
    105           %>
    106           <td width="70%" valign="top">
    107              <table>
    108                <tr>
    109                  <td rowspan="5"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
    110                </tr>
    111                <tr>
    112                  <td><B><%=item.getName() %></B></td> 
    113                </tr>
    114                <tr>
    115                  <td>产地:<%=item.getCity()%></td>
    116                </tr>
    117                <tr>
    118                  <td>价格:<%=item.getPrice() %></td>
    119                </tr>
    120                <tr>
    121                  <td>购买数量:<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" onclick="add();">+</span></td>
    122                </tr> 
    123              </table>
    124              <div id="cart">
    125                <img src="images/buy_now.png"><a href="javascript:selflog_show(<%=item.getId()%>)"><img src="images/in_cart.png"></a><a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
    126              </div>
    127           </td>
    128           <% 
    129             }
    130           %>
    131           <% 
    132               String list ="";
    133               //从客户端获得Cookies集合
    134               Cookie[] cookies = request.getCookies();
    135               //遍历这个Cookies集合
    136               if(cookies!=null&&cookies.length>0)
    137               {
    138                   for(Cookie c:cookies)
    139                   {
    140                       if(c.getName().equals("ListViewCookie"))
    141                       {
    142                          list = c.getValue();
    143                       }
    144                   }
    145               }
    146               
    147               list+=request.getParameter("id")+",";
    148               //如果浏览记录超过1000条,清零.
    149               String[] arr = list.split(",");
    150               if(arr!=null&&arr.length>0)
    151               {
    152                   if(arr.length>=1000)
    153                   {
    154                       list="";
    155                   }
    156               }
    157               Cookie cookie = new Cookie("ListViewCookie",list);
    158               response.addCookie(cookie);
    159           
    160           %>
    161           <!-- 浏览过的商品 -->
    162           <td width="30%" bgcolor="#EEE" align="center">
    163              <br>
    164              <b><font color="#FF7F00">您浏览过的商品</font></b><br>
    165              <!-- 循环开始 -->
    166              <% 
    167                 ArrayList<Items> itemlist = itemDao.getViewList(list);
    168                 if(itemlist!=null&&itemlist.size()>0 )
    169                 {
    170                    System.out.println("itemlist.size="+itemlist.size());
    171                    for(Items i:itemlist)
    172                    {
    173                          
    174              %>
    175              <div>
    176              <dl>
    177                <dt>
    178                  <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
    179                </dt>
    180                <dd class="dd_name"><%=i.getName() %></dd> 
    181                <dd class="dd_city">产地:<%=i.getCity() %>&nbsp;&nbsp;价格:<%=i.getPrice() %></dd> 
    182              </dl>
    183              </div>
    184              <% 
    185                    }
    186                 }
    187              %>
    188              <!-- 循环结束 -->
    189           </td>
    190         </tr>
    191       </table>
    192     </center>
    193   </body>
    194 </html>

    success.jsp

      1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
      2 <%@ page import="entity.Items"%>
      3 <%@ page import="dao.ItemsDAO"%>
      4 <%
      5 String path = request.getContextPath();
      6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      7 %>
      8 
      9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     10 <html>
     11   <head>
     12     <base href="<%=basePath%>">
     13     
     14     <title>My JSP 'details.jsp' starting page</title>
     15     
     16     <meta http-equiv="pragma" content="no-cache">
     17     <meta http-equiv="cache-control" content="no-cache">
     18     <meta http-equiv="expires" content="0">    
     19     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     20     <meta http-equiv="description" content="This is my page">
     21     <!--
     22     <link rel="stylesheet" type="text/css" href="styles.css">
     23     -->
     24     <link href="css/main.css" rel="stylesheet" type="text/css">
     25     <script type="text/javascript" src="js/lhgcore.js"></script>
     26     <script type="text/javascript" src="js/lhgdialog.js"></script>
     27     <script type="text/javascript">
     28       function selflog_show(id)//id要购买的商品编号 ,num购买商品数量,&action=add添加商品进购物车,path是项目的根目录,服务器的根目录:WebRoot
     29       { 
     30          var num =  document.getElementById("number").value; 
     31          J.dialog.get({id: 'haoyue_creat',title: '购物成功', 600,height:400, link: '<%=path%>/servlet/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
     32       }
     33       function add()
     34       {
     35          var num = parseInt(document.getElementById("number").value);
     36          if(num<100)
     37          {
     38             document.getElementById("number").value = ++num;
     39          }
     40       }
     41       function sub()
     42       {
     43          var num = parseInt(document.getElementById("number").value);
     44          if(num>1)
     45          {
     46             document.getElementById("number").value = --num;
     47          }
     48       }
     49      
     50     </script>
     51     
     52     <style type="text/css">
     53        hr{
     54          
     55          border-color:FF7F00; 
     56        }
     57        
     58        div{
     59           float:left;
     60           margin-left: 30px;
     61           margin-right:30px;
     62           margin-top: 5px;
     63           margin-bottom: 5px;
     64          
     65        }
     66        div dd{
     67           margin:0px;
     68           font-size:10pt;
     69        }
     70        div dd.dd_name
     71        {
     72           color:blue;
     73        }
     74        div dd.dd_city
     75        {
     76           color:#000;
     77        }
     78        div #cart
     79        {
     80          margin:0px auto;
     81          text-align:right; 
     82        }
     83        span{
     84          padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer;
     85        }
     86        a{
     87           text-decoration: none; 
     88        }
     89     </style>
     90   </head>
     91   
     92   <body>
     93     <h1>商品详情</h1>
     94     <a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
     95     <hr>
     96     <center>
     97       <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
     98         <tr>
     99           <!-- 商品详情 -->
    100           <% 
    101              ItemsDAO itemDao = new ItemsDAO();
    102              Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
    103              if(item!=null)
    104              {
    105           %>
    106           <td width="70%" valign="top">
    107              <table>
    108                <tr>
    109                  <td rowspan="5"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
    110                </tr>
    111                <tr>
    112                  <td><B><%=item.getName() %></B></td> 
    113                </tr>
    114                <tr>
    115                  <td>产地:<%=item.getCity()%></td>
    116                </tr>
    117                <tr>
    118                  <td>价格:<%=item.getPrice() %></td>
    119                </tr>
    120                <tr>
    121                  <td>购买数量:<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" onclick="add();">+</span></td>
    122                </tr> 
    123              </table>
    124              <div id="cart">
    125                <img src="images/buy_now.png"><a href="javascript:selflog_show(<%=item.getId()%>)"><img src="images/in_cart.png"></a><a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
    126              </div>
    127           </td>
    128           <% 
    129             }
    130           %>
    131           <% 
    132               String list ="";
    133               //从客户端获得Cookies集合
    134               Cookie[] cookies = request.getCookies();
    135               //遍历这个Cookies集合
    136               if(cookies!=null&&cookies.length>0)
    137               {
    138                   for(Cookie c:cookies)
    139                   {
    140                       if(c.getName().equals("ListViewCookie"))
    141                       {
    142                          list = c.getValue();
    143                       }
    144                   }
    145               }
    146               
    147               list+=request.getParameter("id")+",";
    148               //如果浏览记录超过1000条,清零.
    149               String[] arr = list.split(",");
    150               if(arr!=null&&arr.length>0)
    151               {
    152                   if(arr.length>=1000)
    153                   {
    154                       list="";
    155                   }
    156               }
    157               Cookie cookie = new Cookie("ListViewCookie",list);
    158               response.addCookie(cookie);
    159           
    160           %>
    161           <!-- 浏览过的商品 -->
    162           <td width="30%" bgcolor="#EEE" align="center">
    163              <br>
    164              <b><font color="#FF7F00">您浏览过的商品</font></b><br>
    165              <!-- 循环开始 -->
    166              <% 
    167                 ArrayList<Items> itemlist = itemDao.getViewList(list);
    168                 if(itemlist!=null&&itemlist.size()>0 )
    169                 {
    170                    System.out.println("itemlist.size="+itemlist.size());
    171                    for(Items i:itemlist)
    172                    {
    173                          
    174              %>
    175              <div>
    176              <dl>
    177                <dt>
    178                  <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
    179                </dt>
    180                <dd class="dd_name"><%=i.getName() %></dd> 
    181                <dd class="dd_city">产地:<%=i.getCity() %>&nbsp;&nbsp;价格:<%=i.getPrice() %></dd> 
    182              </dl>
    183              </div>
    184              <% 
    185                    }
    186                 }
    187              %>
    188              <!-- 循环结束 -->
    189           </td>
    190         </tr>
    191       </table>
    192     </center>
    193   </body>
    194 </html>

    failure.jsp

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'success.jsp' starting page</title>
    13       <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21 
    22   </head>
    23   
    24   <body>
    25     <center>
    26       <img src="images/add_cart_failure.jpg"/>
    27       <hr>
    28       
    29       <br>
    30       <br>
    31       <br>
    32       
    33     </center>
    34   </body>
    35 </html>

     显示购物车

    商品删除

    带有确认功能的对话框

  • 相关阅读:
    苹果输入手机号变用户的名字
    iOS 关于UITableView的黑科技
    iOS 详解NSObject协议
    iOS 用xib自定义View
    iOS 关于定位你该注意的那些事
    iOS 内存泄漏
    Swift应用案例 2.闭包入门到精通
    Swift应用案例 1.无限轮播
    多库共存-冲突问题
    多库共存-冲突问题
  • 原文地址:https://www.cnblogs.com/songsongblue/p/9757088.html
Copyright © 2011-2022 走看看