/*集大成者,美若天成*/ 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。这样就可以了。
最后我们看一下成果。
时间: 2024-10-09 21:41:29