/*集大成者,美若天成*/ package cart; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Map; import java.util.TreeMap; import util.JDBCUtil; /* 購物車類 */ public class Cart { /* 屬性:商品,採用Map;Key爲商品編號,Value爲商品 */ private Map<Integer, Product> product =new TreeMap<Integer, Product>(); Connection conn = null; Statement stat = null; ResultSet rs = null; PreparedStatement prstat = null; /* 根據商品編號向購物車添加商品 */ public void addProduct(int id) throws SQLException{ conn = JDBCUtil.getConnection(); /* 與數據庫建立連接 */ stat = conn.createStatement(); String sql = "select * from product"; rs = stat.executeQuery(sql); /* 從ResultSet獲取商品信息,加入Map中 */ while(rs.next()){ Product teppro =new Product( rs.getInt("idproduct"), rs.getString("name"), rs.getString("brand"), rs.getInt("price") ); product.put(teppro.getId(), teppro); } /* foreach遍歷Map */ for(Map.Entry<Integer, Product> pro : product.entrySet()) { int pid = pro.getKey(); if(pid == id){ /* 找到要加入的商品id */ sql = "select * from cart where idproduct = "+pid; System.out.println(sql); rs = stat.executeQuery(sql); /* */ /* 查詢購物中是否已存在該商品 */ if(rs.next()){ int amo = 1 + rs.getInt("amount") ; /* 商品數量加一 */ sql = "update cart set amount = ? where idproduct = ?"; System.out.println(sql); prstat = conn.prepareStatement(sql); prstat.setInt(1, amo); prstat.setInt(2, pid); prstat.execute(); /* 設置單品總價 */ sql = "update cart set total = ? where idproduct = ?"; prstat = conn.prepareStatement(sql); prstat.setInt(1, amo*rs.getInt("price")); prstat.setInt(2, pid); prstat.execute(); }else { /* 當購物車中不存在該商品,添加該商品 */ Product p = pro.getValue();System.out.println(p.toString()); sql = "insert into cart(idproduct,name,brand,price,amount,total) " + "values(?,?,?,?,?,?)"; prstat = conn.prepareStatement(sql); prstat.setInt(1, p.getId()); prstat.setString(2, p.getName()); prstat.setString(3, p.getBrand()); int pr = p.getPrice(); prstat.setInt(4,pr); prstat.setInt(5, 1);/* 商品個數爲1 */ prstat.setInt(6,pr); prstat.execute(); } } } JDBCUtil.closeConnection(conn); } /* 清除購物車所有商品 */ public void clearCart() throws SQLException{ conn = JDBCUtil.getConnection(); stat = conn.createStatement(); String sql = "select * from cart"; rs = stat.executeQuery(sql); while(rs.next()){ Product teppro =new Product( rs.getInt("idproduct"), rs.getString("name"), rs.getString("brand"), rs.getInt("price") ); product.put(teppro.getId(), teppro); } for(Map.Entry<Integer, Product> pro : product.entrySet()) { int pid = pro.getKey(); sql = "delete from cart where idproduct = ? "; prstat = conn.prepareStatement(sql); prstat.setInt(1, pid); prstat.execute(); } JDBCUtil.closeConnection(conn); } /* 清除購物車單一商品 */ public void clearProduct(int id) throws SQLException{ conn = JDBCUtil.getConnection(); stat = conn.createStatement(); String sql = "select * from cart"; rs = stat.executeQuery(sql); while(rs.next()){ Product teppro =new Product( rs.getInt("idproduct"), rs.getString("name"), rs.getString("brand"), rs.getInt("price") ); product.put(teppro.getId(), teppro); } for(Map.Entry<Integer, Product> pro : product.entrySet()) { int pid = pro.getKey(); if(id==pid){ sql = "delete from cart where idproduct = ? "; prstat = conn.prepareStatement(sql); prstat.setInt(1, pid); prstat.execute(); } } JDBCUtil.closeConnection(conn); } /*修改單品數量*/ public void changeAmount(int idp ,int amon) throws SQLException{ conn = JDBCUtil.getConnection(); stat = conn.createStatement(); String sql = "select * from cart"; rs = stat.executeQuery(sql); while(rs.next()){ Product teppro =new Product( rs.getInt("idproduct"), rs.getString("name"), rs.getString("brand"), rs.getInt("price") ); product.put(teppro.getId(), teppro); } for(Map.Entry<Integer, Product> pro : product.entrySet()) { int pid = pro.getKey();System.out.println(pid); if(pid==idp){ sql = "update cart set amount = ? where idproduct = ? "; prstat = conn.prepareStatement(sql); prstat.setInt(1, amon); prstat.setInt(2 , idp); prstat.execute(); } } JDBCUtil.closeConnection(conn); } }
package cart; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import util.JDBCUtil; /* 用戶類 */ public class User { private String username; private String password; Connection conn = null; Statement stat = null; ResultSet rs = null; /* 驗證登錄信息 */ public boolean login() throws SQLException{ Connection conn = JDBCUtil.getConnection(); Statement stat = conn.createStatement(); String sql = "select * from user"; ResultSet rs = stat.executeQuery(sql); while(rs.next()){ User us = new User(rs.getString("username"),rs.getString("psd"));us.toString(); if(us.equals(this)){ return true; } }return false; } @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } }
package cart; /* 商品類 */ public class Product { private int id;/* 商品編號 */ private String name;/*商品名稱*/ private String brand;/*商品品牌*/ private int price;/*商品價格*/ /* 構造函數 */ public Product(int id, String name, String brand, int price) { super(); this.id = id; this.name = name; this.brand = brand; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Product [id=" + id + ", name=" + name + ", brand=" + brand + ", price=" + price + "]"; } }
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtil { private static String driverName = "com.mysql.jdbc.Driver"; private static String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK"; private static String userName = "root";//根據自己數據庫 private static String password = "12345"; /* 註冊驅動 */ public static void registerDriver() { try { Class.forName(driverName); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("找不到驅動"); } } /* 連接數據庫 */ public static Connection getConnection() throws SQLException { registerDriver(); Connection conn = null; System.out.println("正在連接數據庫..."); conn = DriverManager.getConnection(URL, userName, password); System.out.println("數據庫已連接!"); return conn; } /* 關閉連接 */ public static void closeConnection(Connection conn) { System.out.println("正在釋放所有資源..."); try { if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } /* * 釋放所有資源 */ public static void realeaseAll(Statement st,Connection conn){ if (st!=null){ try { st.close(); st = null; } catch (SQLException e) { e.printStackTrace(); } } closeConnection(conn); } }
<%@page import="java.util.LinkedList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*,util.JDBCUtil,cart.Product,java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>商品信息</title> </head> <!-- 設置背景圖片 --> <style type="text/css"> body{ background-image: url(background.jpg); background-size :100%; } </style> <!-- 設置字體 --> <style type="text/css"> #product { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; width:70%; border-collapse:collapse; } #product td, #product th { font-size:1em; border:1px solid #98bf21; padding:3px 7px 2px 7px; } #product th { font-size:1.1em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#A7C942; color:#ffffff; } #product tr.blt td { color:#000000; background-color:#FFFFFF; } #product tr.alt td { color:#000000; background-color:#EAF2D3; } </style> <!-- 建立數據庫連接,獲取所有商品信息--> <% Connection conn = JDBCUtil.getConnection(); Statement stat = conn.createStatement(); String sql = "select * from product"; ResultSet rs = stat.executeQuery(sql); %> <!-- 顯示商品信息--> <body> <% String username = null; %> <!-- 顯示歡迎信息 --> <div align="center"> <br> <% username = request.getParameter("username"); if(username == null) out.println("<a href='login.jsp'>用戶登錄 </a> "); else out.println("歡迎您,"+ username +"    <a href='operate.jsp?&op=exit&username="+username+"'>退出 </a> "); %> </div> <!-- 輸出商品信息 --> <div align="center"> <table id="product" border="2" width="400"> <tr class="alt" > <td align="center" width="90">商品編號</td> <td align="center" width="90">商品名稱</td> <td align="center" width="90">商品品牌</td> <td align="center" width="90">商品價格</td> <td align="center" width="90">點擊購買</td> </tr> <% /* 將商品信息讀出 */ List<Product> pl = new LinkedList<Product>(); while(rs.next()){ pl.add(new Product( rs.getInt("idproduct"), rs.getString("name"), rs.getString("brand"), rs.getInt("price") )); } int i=1; for(Product pro:pl){ if(i%2==0)out.println("<tr class='alt' >"); else out.println("<tr class='blt' >"); i++; out.println("<td align='center' width='90'>" +pro.getId()+" </td>"); out.println("<td align='center' width='90'>" +pro.getName()+" </td>"); out.println("<td align='center' width='90'>" +pro.getBrand()+" </td>"); out.println("<td align='center' width='90'>¥" +pro.getPrice()+" </td>"); out.println("<td><a href='operate.jsp?op=add&id="+pro.getId()+"&username="+username+"'>加入購物車</a></td>"); out.println("</tr>"); } %> </table> </div> <!--查看購物、清空購物車 --> <div align="center"> <br> <% out.println("<a href='cart.jsp?username="+username+"'>查看購物車 </a>     "); out.println(" <a href='operate.jsp?op=clear&username="+username+"'>清空購物車</a> "); %> </div> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用戶登錄</title> </head> <!-- 設置背景圖片 --> <style type="text/css"> body{ background-image: url(background.jpg); background-size :100%; } </style> <!-- 設置字體--> <style type="text/css"> p.serif{font-family:Arial,Verdana,Sans-serif} </style> <body> <div align="center"> <form name="postForm" action="dologin.jsp" method="get"> <p class="serif">用戶名 :<input type="text" name="username" /></p> <p class="serif">密    碼:<input type="password" name="password" /></p> <input type="submit" value="登錄" />         <a href="index.jsp">返回 </a> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用戶登錄</title> </head> <!-- 設置背景圖片 --> <style type="text/css"> body{ background-image: url(background.jpg); background-size :100%; } </style> <!-- 設置字體--> <style type="text/css"> p.serif{font-family:Arial,Verdana,Sans-serif} </style> <body> <div align="center"> <form name="postForm" action="dologin.jsp" method="get"> <p class="serif">用戶名 :<input type="text" name="username" /></p> <p class="serif">密    碼:<input type="password" name="password" /></p> <input type="submit" value="登錄" />         <a href="index.jsp">返回 </a> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import= "cart.Cart" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>operating</title> </head> <body> <!-- 連接數據庫,計算總價 --> <style type="text/css"> body{ background-image: url(background.jpg); background-size :100%; } </style> <script> function RepNumber(obj) { var reg = /^[\d]+$/g; if (!reg.test(obj.value)) { var txt = obj.value; txt.replace(/[^0-9]+/, function (char, index, val) {//匹配第一次非數字字符 obj.value = val.replace(/\D/g, "");//將非數字字符替換成"" var rtextRange = null; if (obj.setSelectionRange) { obj.setSelectionRange(index, index); } else {//支持ie rtextRange = obj.createTextRange(); rtextRange.moveStart('character', index); rtextRange.collapse(true); rtextRange.select(); } }) } } </script> <% String op = null; String username = null; String number = null; int id = 0; Cart cart = new Cart(); op = request.getParameter("op"); username = request.getParameter("username"); if( !op.equals("exit") && (username == null || username.equals("null") || username.equals(null))){ out.println("     請登錄...."); response.setHeader("Refresh","1;URL=index.jsp"); }else if(op.equals("add")){ id = Integer.parseInt(request.getParameter("id")); cart.addProduct(id); out.println("     正在添加商品...."); response.setHeader("Refresh","0;URL=cart.jsp?username="+username); }else if(op.equals("clear")){ cart.clearCart(); out.println("     正在清除購物車...."); response.setHeader("Refresh","0;URL=cart.jsp?username="+username); }else if(op.equals("pay")){ out.println("     正在結算...."); response.setHeader("Refresh","0;URL=pay.jsp?username="+username); }else if(op.equals("exit")){ cart.clearCart(); out.println("     正在登出...."); response.setHeader("Refresh","0;URL=index.jsp"); }else if(op.equals("delete")){ id = Integer.parseInt(request.getParameter("id")); cart.clearProduct(id); out.println("     正在退回...."); response.setHeader("Refresh","0;URL=cart.jsp?username="+username); }else if(op.equals("paid")){ out.println("<div align='center' >"); out.println("     已經成功付款,順豐快遞將盡快爲您配送...."); out.println("<div>"); cart.clearCart(); response.setHeader("Refresh","2;URL=index.jsp?username="+username); }else if(op.equals("change")){ id = Integer.parseInt(request.getParameter("id")); out.println("<div align='center' >"); out.println("<form name='postForm' action='operate.jsp' method='get'> "); out.println("請輸入數量:"); out.println("<input type='text' name='number' onkeyup='javascript:RepNumber(this)'/>"); out.println("<input type=hidden name='id' value="+ id+">" ); out.println("<input type=hidden name='op' value=changed>" ); out.println(" <input type=hidden name='username' value="+ username+">"); out.println(" <input type='submit' value='提交' /> "); out.println("</form>"); out.println("<div>"); }else if(op.equals("changed")){ id = Integer.parseInt(request.getParameter("id")); cart.changeAmount(id,Integer.parseInt(request.getParameter("number"))); out.println("     修改成功...."); response.setHeader("Refresh","0;URL=cart.jsp?username="+username); } %> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*,util.JDBCUtil,cart.*,java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> 支付頁面 </title> </head> <body> <% String username = request.getParameter("username"); %> <!-- 設置背景圖片 --> <style type="text/css"> body{ background-image: url(background.jpg); background-size :100%; } </style> <!-- 連接數據庫,計算總價 --> <div align="center" > <% Connection conn = JDBCUtil.getConnection(); Statement stat = conn.createStatement(); String sql = "select * from cart"; ResultSet rs = stat.executeQuery(sql); int sum = 0; while(rs.next()){ sum+=rs.getInt("price")*rs.getInt("amount"); } out.println("   需支付¥ :"+sum); JDBCUtil.closeConnection(conn); %> </div> <!-- 選擇收貨地址 --> <div align="center" > 選擇送貨地址: <select > <option value="1" selected>福建</option> </select>     <select > <option value="1" selected>廈門</option> <option value="2" >泉州</option> <option value="3">漳州</option> </select>     具體地址 :<input type="text" name="address" size=20 />     <% out.println("<a href='operate.jsp?op=paid&username="+username+"'>確定付款</a>     "); out.println("<a href='cart.jsp?username="+username+"'>返回購物車</a>     "); %> </div> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*,util.JDBCUtil,cart.Product,java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>我的購物車</title> </head> <!-- 設置背景 --> <style type="text/css"> body{ background-image: url(background.jpg); background-size :100%; } </style> <!-- 表格美化 --> <style type="text/css"> #product { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; width:70%; border-collapse:collapse; } #product td, #product th { font-size:1em; border:1px solid #98bf21; padding:3px 7px 2px 7px; } #product th { font-size:1.1em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#A7C942; color:#ffffff; } #product tr.blt td { color:#000000; background-color:#FFFFFF; } #product tr.alt td { color:#000000; background-color:#EAF2D3; } </style> <!-- 連接數據庫 --> <% Connection conn = JDBCUtil.getConnection(); Statement stat = conn.createStatement(); String sql = "select * from cart"; ResultSet rs = stat.executeQuery(sql); String username = null; %> <body> <div align="center"> <% username = request.getParameter("username"); if(username == null || username.equals("null") || username.equals(null)){ out.println("     請登錄...."); response.setHeader("Refresh","0;URL=index.jsp"); }else out.println("歡迎您,"+ username +"    <a href='operate.jsp?op=exit&username"+username+"'>退出 </a> "); %> </div> <!-- 輸出購物車內容 --> <div align="center"> <table border="2" width="600"> <tr class='alt'> <td align="center" width="90">商品編號</td> <td align="center" width="90">商品名稱</td> <td align="center" width="90">商品品牌</td> <td align="center" width="90">商品價格</td> <td align="center" width="90">購買數量</td> <td align="center" width="90">單品總價</td> <td align="center" width="90">退回商品</td> <td align="center" width="90">修改數量</td> </tr> <% int j=1;int sum=0; while(rs.next()){ int k,p,m; if(j%2==0)out.println("<tr class='alt' >"); else out.println("<tr class='blt' >"); j++; out.println("<td align='center' width='90'>" +(k=rs.getInt("idproduct"))+" </td>"); out.println("<td align='center' width='90'>" +rs.getString("name")+" </td>"); out.println("<td align='center' width='90'>" +rs.getString("brand")+" </td>"); out.println("<td align='center' width='90'>" +(p=rs.getInt("price"))+" </td>"); out.println("<td align='center' width='90'>" +(m=rs.getInt("amount"))+" </td>"); out.println("<td align='center' width='90'>¥" +p*m+" </td>"); out.println("<td align='center' width='90'>"+ "<a href='operate.jsp?op=delete&username="+username+"&id="+ k+"'>點擊退回</a></td>"); out.println("<td align='center' width='90'>"+ "<a href='operate.jsp?op=change&username="+username+"&id="+ k+"'>點擊修改</a></td>"); out.println("</tr>"); sum+=p*m; } %> </table> </div> <div align="center"> <br> <% out.println("總計:¥ "+sum+"     "); out.println(" <a href='index.jsp?username="+username+"'>繼續購物 </a>     "); out.println("<a href='operate.jsp?op=clear&username="+username+"'>清空購物車</a>     "); out.println(" <a href='operate.jsp?op=pay&username="+username+"'>結算</a>     "); %> </div> </body> </html>
這是網站採用的背景,個人覺得還不錯。
這樣代碼部分就完工了。雖然還是缺少某些功能,以及有些處理不恰當,但總體還是可以的。接下來我們往數據庫添加內容。注意網頁字符集和數據庫字符集,可能會出現亂碼。
接着我們下載花生殼並安裝好,申請一個免費域名(要花1元錢實名認證來着),然後將你的ip映射到外網。
由於我的tomcat的8080端口被佔用了,所以改成了8088端口。那麼怎麼改端口號還有需要改什麼,網上教程有很多,我這裏簡單陳述一下。進入tomcat文件夾,打開conf文件夾裏的server.xml,搜索一下第一個8080,將其改成8088或其他,如果沒被佔用就不必改了。除此之外,搜索localhost並替換成xxxx.xicp.net。這樣就可以了。
最後我們看一下成果。