源码: 韩顺平 j2ee myshopping(MODEL2)
1、数据库链接和数据库CRUD类
1 package fafa.shop.util; 2 3 import java.sql.*; 4 5 public class DBUtil { 6 private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; 7 private static final String DBURL = "jdbc:mysql://localhost:3306/test" ; 8 private static final String DBUSER = "root" ; 9 private static final String DBPASS = "123456" ; 10 11 private static Connection conn = null ; 12 13 //外部取得连接 14 public static Connection getConnection() throws Exception { 15 Class.forName(DBDRIVER) ; 16 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS) ; 17 return conn ; 18 } 19 20 //关闭连接 21 public static void close(ResultSet rs, Statement ps, Connection ct){ 22 try { 23 if (rs!=null){ 24 rs.close() ; 25 } 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } 29 try { 30 if (ps!=null){ 31 ps.close() ; 32 } 33 } catch (SQLException e) { 34 e.printStackTrace(); 35 } 36 try { 37 if (ct!=null){ 38 ct.close() ; 39 } 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } 43 } 44 }
1 package fafa.shop.util; 2 3 import java.sql.*; 4 import java.util.ArrayList; 5 6 public class SqlHelper { 7 8 private static Connection ct = null ; 9 private static PreparedStatement ps = null ; 10 private static ResultSet rs = null ; 11 12 /** 13 * 执行sql查询 返回结果集 14 * @param sql 15 * @param param 16 * @return rs 17 */ 18 public ResultSet executeQuery(String sql, String []param){ 19 try { 20 //取得连接 21 ct = DBUtil.getConnection() ; 22 //sql预处理 23 ps = ct.prepareStatement(sql) ; 24 //如果参数存在,循环赋值 25 if (param!=null && !param.equals("")){ 26 for(int i=0; i<param.length; i++){ 27 ps.setString(i+1, param[i]) ; 28 } 29 } 30 //执行sql 31 rs = ps.executeQuery() ; 32 } catch (Exception e) { //异常抛出 33 e.printStackTrace() ; 34 } 35 //返回结果集 36 return rs ; 37 } 38 39 /** 40 * 执行查询 返回集合 41 * @param sql 42 * @param param 43 * @return all 集合 44 */ 45 public ArrayList<Object> executeQuery1(String sql, String []param){ 46 //定义集合接收 47 ArrayList<Object> all = new ArrayList<Object>() ; 48 try { 49 //取得连接 50 ct = DBUtil.getConnection() ; 51 //预处理 52 ps = ct.prepareStatement(sql) ; 53 //如果存在 循环赋值 54 if (param!=null && !param.equals("")){ 55 for(int i=0; i<param.length; i++){ 56 ps.setString(i+1, param[i]) ; 57 } 58 } 59 //执行sql语句 取得结果集 60 rs = ps.executeQuery() ; 61 //取得字段列表 62 ResultSetMetaData rsmd = rs.getMetaData() ; 63 //取得字段数量 64 int columnNum = rsmd.getColumnCount() ; 65 //循环取值 66 while(rs.next()){ 67 Object []objects = new Object[columnNum] ; 68 for(int i=0; i<objects.length; i++){ 69 objects[i] = rs.getObject(i+1) ;//返回对象数组 70 } 71 //循环加入集合 72 all.add(objects) ; 73 } 74 } catch (Exception e) { 75 e.printStackTrace(); 76 }finally{ 77 //关闭连接 78 DBUtil.close(rs, ps, ct) ; 79 } 80 //返回集合 81 return all; 82 } 83 }
2、用户需要登录 Servlet去接收并验证
1 package fafa.shop.controller; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 6 import javax.servlet.*; 7 import javax.servlet.http.*; 8 9 import fafa.shop.doamin.User; 10 import fafa.shop.service.BookService; 11 import fafa.shop.service.MyCart; 12 import fafa.shop.service.UserService; 13 14 @SuppressWarnings("serial") 15 public class GoHallUI extends HttpServlet { 16 17 public void doGet(HttpServletRequest request, HttpServletResponse response) 18 throws ServletException, IOException { 19 request.setCharacterEncoding("GBK") ; 20 //取得登陆表单的数据 21 String userid = request.getParameter("userid") ; 22 String password = request.getParameter("password") ; 23 24 //创建user对象,构造方法设置用户ID password 25 User user = new User(Integer.parseInt(userid), password) ; 26 27 //使用UserService验证数据 28 UserService us = new UserService() ; 29 if (us.checkUser(user)){ 30 //数据库验证成功后,写入session 31 request.getSession().setAttribute("loginUser", user) ; 32 //用户登录成功 就创建购物车 存入session 33 MyCart mycart = new MyCart() ; 34 request.getSession().setAttribute("mycart", mycart) ; 35 36 //给hall.jsp 输出数据 37 BookService bookservice = new BookService() ; 38 ArrayList<?> all = bookservice.getAllBook() ; 39 request.setAttribute("all", all) ; 40 41 //成功跳转 hall.jsp 购物大厅页 42 request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response) ; 43 }else{ 44 //失败跳转 login.jsp 登陆页 45 request.setAttribute("error", "用户名或密码错误") ; 46 request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response) ; 47 } 48 } 49 50 public void doPost(HttpServletRequest request, HttpServletResponse response) 51 throws ServletException, IOException { 52 this.doGet(request, response) ; 53 } 54 }
3、user bean类 和 userService CRUD类
1 package fafa.shop.doamin; 2 /** 3 * User Bean 4 * @author administrator 5 */ 6 public class User { 7 private int id ; 8 private String username ; 9 private String password ; 10 private String email ; 11 private String tel ; 12 private int grade ; 13 14 public User(int id, String password) { 15 super(); 16 this.id = id; 17 this.password = password; 18 } 19 public int getId() { 20 return id; 21 } 22 public void setId(int id) { 23 this.id = id; 24 } 25 public String getUsername() { 26 return username; 27 } 28 public void setUsername(String username) { 29 this.username = username; 30 } 31 public String getPassword() { 32 return password; 33 } 34 public void setPassword(String password) { 35 this.password = password; 36 } 37 public String getEmail() { 38 return email; 39 } 40 public void setEmail(String email) { 41 this.email = email; 42 } 43 public String getTel() { 44 return tel; 45 } 46 public void setTel(String tel) { 47 this.tel = tel; 48 } 49 public int getGrade() { 50 return grade; 51 } 52 public void setGrade(int grade) { 53 this.grade = grade; 54 } 55 56 }
1 package fafa.shop.service; 2 3 import java.util.ArrayList; 4 5 import fafa.shop.doamin.User; 6 import fafa.shop.util.SqlHelper; 7 8 public class UserService { 9 10 //验证用户 11 public boolean checkUser(User user) { 12 //到数据库验证 13 String sql = "SELECT id, username, password, email, grade FROM user WHERE username=? AND password=?" ; 14 String param[] = {user.getUsername(), user.getPassword()} ; 15 //取得查询后的结果集 16 ArrayList<?> all = (ArrayList<?>) new SqlHelper().executeQuery(sql, param) ; 17 if (all.size() == 0){ 18 return false ; 19 }else{ 20 Object []obj = (Object[]) all.get(0) ; 21 user.setId((Integer) obj[0]) ; 22 user.setUsername((String) obj[1]) ; 23 user.setTel((String) obj[3]) ; 24 user.setGrade((Integer) obj[4]) ; 25 return true ; 26 } 27 } 28 }
3、购物车类
1 package fafa.shop.service; 2 3 import java.util.*; 4 5 import fafa.shop.doamin.Book; 6 7 public class MyCart { 8 //定义hashmap接收书 9 HashMap<String, Book> hm = new HashMap<String, Book>() ; 10 11 public void addBook2(String id){ 12 if (hm.containsKey(id)){//判断此ID是否存在 13 Book book = hm.get(id) ; //其实拿出来的是前一本书 修改购买数量 14 int shoppingNum = book.getShoppingNum() ; 15 book.setShoppingNum(shoppingNum + 1) ; 16 }else{ 17 hm.put(id, new BookService().getBookById(id)) ; //如果是第一本书则直接加入HashMap 18 } 19 } 20 21 //添加书 22 public void addBook(String id, Book book){ 23 if (hm.containsKey(id)){ //判断此ID是否存在 24 book = hm.get(id) ; //其实拿出来的是前一本书 修改购买数量 25 //如果购物车中存在这本书 ,那么则把购买数量加1 26 int shoppingNum = book.getShoppingNum() ; 27 book.setShoppingNum(shoppingNum + 1) ; 28 }else{ 29 hm.put(id, book) ; 30 } 31 } 32 //删除书 33 public void delBook(String id){ 34 hm.remove(id) ; 35 } 36 //更新书 37 public void updateBook(String id, String nums){ 38 Book book = hm.get(id) ; 39 book.setShoppingNum(Integer.parseInt(nums)) ; 40 41 } 42 43 //显示购物车中的所有商品 44 public ArrayList<Book> showMycart(){ 45 Iterator<String> iter = hm.keySet().iterator() ; 46 ArrayList<Book> all = new ArrayList<Book>() ; 47 while(iter.hasNext()){ 48 String key = (String) iter.next() ; 49 Book book = hm.get(key) ; 50 all.add(book) ; 51 } 52 return all ; 53 } 54 55 //计算总价 56 public float getTotalPrice(){ 57 float totalPrice = 0.0f ; 58 Iterator<String> iterator = hm.keySet().iterator() ; 59 while(iterator.hasNext()){ 60 String bookId = (String) iterator.next() ; 61 Book book = hm.get(bookId) ; 62 totalPrice += book.getPrice() * book.getShoppingNum() ; 63 } 64 return totalPrice; 65 } 66 67 //清空购物车 68 public void clearBook(){ 69 hm.clear() ; 70 } 71 }
4、购物大厅数据,book bean类 和 bookService 类
1 package fafa.shop.doamin; 2 /** 3 * Book bean 4 * @author administrator 5 */ 6 public class Book { 7 private int id ; 8 private String name ; 9 private String author ; 10 private String publishHouse ; 11 private float price ; 12 private int nums ; 13 private int shoppingNum = 1; //购买数量 14 15 public int getShoppingNum() { 16 return shoppingNum; 17 } 18 public void setShoppingNum(int shoppingNum) { 19 this.shoppingNum = shoppingNum; 20 } 21 public int getId() { 22 return id; 23 } 24 public void setId(int id) { 25 this.id = id; 26 } 27 public String getName() { 28 return name; 29 } 30 public void setName(String name) { 31 this.name = name; 32 } 33 public String getAuthor() { 34 return author; 35 } 36 public void setAuthor(String author) { 37 this.author = author; 38 } 39 public String getPublishHouse() { 40 return publishHouse; 41 } 42 public void setPublishHouse(String publishHouse) { 43 this.publishHouse = publishHouse; 44 } 45 public float getPrice() { 46 return price; 47 } 48 public void setPrice(float price) { 49 this.price = price; 50 } 51 public int getNums() { 52 return nums; 53 } 54 public void setNums(int nums) { 55 this.nums = nums; 56 } 57 58 }
1 package fafa.shop.service; 2 3 import java.util.ArrayList; 4 5 import fafa.shop.doamin.Book; 6 import fafa.shop.util.SqlHelper; 7 8 9 public class BookService { 10 public ArrayList<?> getAllBook(){ 11 String sql = "SELECT * FROM book WHERE bname LIKE '%?%'" ; 12 String param[] = {""} ; 13 ArrayList<?> all = (ArrayList<?>) new SqlHelper().executeQuery(sql, param) ; 14 ArrayList<Book> newall = new ArrayList<Book>(); 15 16 for(int i=0; i<all.size(); i++){ 17 Object obj[] = (Object[]) all.get(i) ; 18 Book book = new Book(); 19 book.setId(Integer.parseInt(obj[0].toString())) ; 20 book.setName(obj[1].toString()) ; 21 book.setPublishHouse(obj[2].toString()) ; 22 book.setAuthor(obj[3].toString()) ; 23 book.setPrice(Float.parseFloat(obj[4].toString())) ; 24 book.setNums(Integer.parseInt(obj[5].toString())) ; 25 newall.add(book); 26 } 27 return newall; 28 } 29 30 //根据ID 去一条数据 31 public Book getBookById(String id){ 32 String sql = "SELECT * FROM book WHERE id=?" ; 33 String param[] = {id} ; 34 ArrayList<?> all = (ArrayList<?>) new SqlHelper().executeQuery(sql, param) ; 35 Book book = new Book(); 36 if (all.size() == 1){ 37 Object []obj = (Object[])all.get(0) ; 38 book.setId(Integer.parseInt(obj[0].toString())) ; 39 book.setName(obj[1].toString()) ; 40 book.setPublishHouse(obj[2].toString()) ; 41 book.setAuthor(obj[3].toString()) ; 42 book.setPrice(Float.parseFloat(obj[4].toString())) ; 43 book.setNums(Integer.parseInt(obj[5].toString())) ; 44 } 45 return book; 46 } 47 }
5、用户点击购买,跳转到购物车界面 购物车中的CRUD Servlet
1 package fafa.shop.controller; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import fafa.shop.service.MyCart; 11 12 @SuppressWarnings("serial") 13 public class GoShowMyCart extends HttpServlet { 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 request.setCharacterEncoding("GBK") ; 17 18 //从Seesion中取出数据 到showMyCart.jsp页面显示 19 MyCart mycart = (MyCart) request.getSession().getAttribute("mycart") ; 20 //把mycart中的书,输出到页面showMyCart.jsp 21 request.setAttribute("booklist", mycart.showMycart()) ; 22 //输出总价 23 request.setAttribute("totalPrice", mycart.getTotalPrice()) ; 24 //跳转到showMyCart.jsp 25 request.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(request, response) ; 26 27 } 28 29 public void doPost(HttpServletRequest request, HttpServletResponse response) 30 throws ServletException, IOException { 31 this.doGet(request, response) ; 32 } 33 34 }
1 package fafa.shop.controller; 2 import java.io.IOException; 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import fafa.shop.service.MyCart; 8 9 /** 10 * 处理购物车请求 11 * @author administrator 12 * 13 */ 14 @SuppressWarnings("serial") 15 public class ShoppingCLservlet extends HttpServlet { 16 17 @Override 18 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 19 throws ServletException, IOException { 20 req.setCharacterEncoding("GBK") ; 21 //获取处理类型 22 String type = req.getParameter("type") ; 23 24 //判断类型 25 if (type.equals("del")){ 26 String id = req.getParameter("id") ; 27 //获取购物车,并删除商品 28 MyCart mycart = (MyCart) req.getSession().getAttribute("mycart") ; 29 mycart.delBook(id) ; 30 //把数据也传递过去 31 req.setAttribute("booklist", mycart.showMycart()) ; 32 //输出总价 33 req.setAttribute("totalPrice", mycart.getTotalPrice()) ; 34 //跳转到购物车jsp页面 35 req.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(req, resp) ; 36 37 }else if(type.equals("add")){ 38 //获取商品编号 39 String id = req.getParameter("id") ; 40 //取出购物车,并添加商品到购物车 41 MyCart mycart = (MyCart) req.getSession().getAttribute("mycart") ; 42 mycart.addBook2(id) ; 43 44 //客户端跳转到 GoShowMyCart 控制器 然后准备数据 传输到 showMyCart.jsp 页面 45 resp.sendRedirect("/sp/GoShowMyCart"); 46 47 }else if (type.equals("update")){ 48 String bookIds[] = req.getParameterValues("id") ; 49 String nums[] = req.getParameterValues("num") ; 50 //取出购物车,并更新数量 51 MyCart mycart = (MyCart) req.getSession().getAttribute("mycart") ; 52 for(int i=0; i<bookIds.length; i++){ 53 mycart.updateBook(bookIds[i], nums[i]) ; 54 } 55 //把mycart中的书,输出到页面showMyCart.jsp 56 req.setAttribute("booklist", mycart.showMycart()) ; 57 //输出总价 58 req.setAttribute("totalPrice", mycart.getTotalPrice()) ; 59 //跳转到购物车jsp页面 60 req.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(req, resp) ; 61 }else if (type.equals("clear")){ 62 //获取购物车,并删除商品 63 MyCart mycart = (MyCart) req.getSession().getAttribute("mycart") ; 64 mycart.clearBook() ; 65 //把数据也传递过去 66 req.setAttribute("booklist", mycart.showMycart()) ; 67 //输出总价 68 req.setAttribute("totalPrice", mycart.getTotalPrice()) ; 69 //跳转到购物车jsp页面 70 req.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(req, resp) ; 71 } 72 } 73 74 @Override 75 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 76 throws ServletException, IOException { 77 super.doGet(req, resp); 78 } 79 }
6、生成订单,跳转到订单页面
1 package fafa.shop.controller; 2 import java.io.IOException; 3 import java.util.ArrayList; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import fafa.shop.service.MyCart; 11 @SuppressWarnings("serial") 12 public class GoMyOrderServlet extends HttpServlet { 13 public void doGet(HttpServletRequest request, HttpServletResponse response) 14 throws ServletException, IOException { 15 request.setCharacterEncoding("GBK") ; 16 //取出购物车, 取得商品信息 和 价格 , 并设置 17 MyCart mycart = (MyCart) request.getSession().getAttribute("mycart") ; 18 ArrayList<?> all = mycart.showMycart() ; 19 float totalPrice = mycart.getTotalPrice() ; 20 request.setAttribute("orderinfo", all) ; 21 request.setAttribute("tatalPrice", totalPrice) ; 22 23 //跳转到 showMyOrder.jsp 显示订单信息 24 request.getRequestDispatcher("/WEB-INF/showMyOrder.jsp").forward(request, response) ; 25 } 26 27 public void doPost(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 this.doGet(request, response) ; 30 } 31 }
1 package fafa.shop.service; 2 3 import java.sql.*; 4 import java.util.ArrayList; 5 6 import fafa.shop.doamin.Book; 7 import fafa.shop.doamin.User; 8 import fafa.shop.util.DBUtil; 9 10 public class OrderService { 11 private Connection ct = null ; 12 private PreparedStatement ps = null ; 13 private ResultSet rs = null ; 14 15 //下订单涉及到两张表, 且有关系 16 public boolean submitOrder(MyCart mycart, User user){ 17 boolean flag = false ; 18 String sql = "INSERT INTO order VALUES(order_seq.nextval, ?, ?, sysdate)"; 19 try{ 20 ct = DBUtil.getConnection() ; //取得连接 21 22 //为了保证两张表的数据在提交时不发生错乱,所以必须升级事务隔离级别,为可串行化。 23 ct.setAutoCommit(false) ; //设置非自动提交事务 ; 24 ct.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE) ; //设置隔离级别为串行化 25 26 ps = ct.prepareStatement(sql) ; //预处理sql 27 ps.setInt(1, user.getId()) ; //设置值 28 ps.setFloat(2, mycart.getTotalPrice()) ;//设置值 29 ps.executeUpdate() ; //执行sql 30 31 //得到刚刚插入订单表的订单号 32 sql = "SELECT order_seq FROM order" ; 33 ps = ct.prepareStatement(sql) ; 34 rs = ps.executeQuery() ; 35 int orderId = 0 ; 36 if (rs.next()){ 37 orderId = rs.getInt(1) ; 38 } 39 //取得上面的 订单ID 生成订单细节表 40 ArrayList<?> all = mycart.showMycart() ; 41 for(int i=0; i<all.size(); i++){ 42 Book book = (Book) all.get(i) ; 43 sql = "INSERT INTO orderItem VALUES(orderItem_seq.nextval, ?, ?, ?)" ; 44 ps = ct.prepareStatement(sql) ; 45 ps.setInt(1, orderId) ; 46 ps.setInt(2, book.getId()) ; 47 ps.setInt(3, book.getShoppingNum()) ; 48 ps.executeUpdate() ; 49 } 50 51 ct.commit() ; //提交事务 52 flag = true ; 53 }catch(Exception e){ 54 try { 55 ct.rollback() ; //事务回滚 56 } catch (SQLException e1) { 57 e1.printStackTrace(); 58 } 59 e.printStackTrace() ; 60 } 61 62 return flag ; 63 } 64 }
7、确认订单 并发送邮件
1 package fafa.shop.controller; 2 import java.io.IOException; 3 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import fafa.shop.doamin.User; 10 import fafa.shop.mail.MailSenderInfo; 11 import fafa.shop.mail.SimpleMailSender; 12 import fafa.shop.service.MyCart; 13 import fafa.shop.service.OrderService; 14 15 16 @SuppressWarnings("serial") 17 public class SubmitOrderServlet extends HttpServlet { 18 public void doGet(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException { 20 request.setCharacterEncoding("GBK") ; 21 //从Session中取出 购物车 和用户信息 22 MyCart mycart = (MyCart) request.getSession().getAttribute("mycart") ; 23 User user = (User) request.getSession().getAttribute("loginUser") ; 24 //实例化 OrderService 对象 25 OrderService orderservice = new OrderService() ; 26 //如果不成功 跳转错误页面 否则跳转 正确页面 27 if ( orderservice.submitOrder(mycart, user) == false ){ 28 request.getRequestDispatcher("/WEB-INF/orderError.jsp") ; 29 }else{ 30 // 这个类主要是设置邮件相关信息 31 MailSenderInfo mailInfo = new MailSenderInfo(); 32 mailInfo.setMailServerHost("smtp.163.com"); //代理发邮件的服务器地址 33 mailInfo.setMailServerPort("25"); //邮件服务器端口 34 mailInfo.setValidate(true); //是否验证 35 mailInfo.setUserName("dafa168@163.com"); //邮件账号 36 mailInfo.setPassword("**********"); //邮箱密码 37 mailInfo.setFromAddress("dafa168@163.com"); //发送邮件邮箱 38 mailInfo.setToAddress("dafa168@126.com"); //接收邮件邮箱 39 mailInfo.setSubject("设置测试邮箱标题 "); //邮件标题 40 mailInfo.setContent("设置邮箱内容测试测试测试测试"); //邮件内容 41 42 // 这个类主要来发送邮件 43 SimpleMailSender sms = new SimpleMailSender(); 44 //sms.sendTextMail(mailInfo);// 发送文体格式 45 sms.sendHtmlMail(mailInfo);// 发送html格式 46 request.getRequestDispatcher("/WEB-INF/showMyOrder.jsp").forward(request, response) ; 47 } 48 } 49 50 public void doPost(HttpServletRequest request, HttpServletResponse response) 51 throws ServletException, IOException { 52 this.doGet(request, response); 53 } 54 }
下面应该跳转到支付界面,付款,以后开发过了就会补上来
需要研究啊