博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网上书城项目
阅读量:6822 次
发布时间:2019-06-26

本文共 46992 字,大约阅读时间需要 156 分钟。

    实习就要结束了,最终要上交的是网上书城项目和一份文档。接下来简要介绍一下项目。

项目是根据三层架构来写,数据访问层(DAO层)、系统业务逻辑控制处理层(servlet层)、和界面层(jsp)。

首先在DAO层构造好SQL语句,对数据库进行操作,在servlet层调用Dao层相关方法进行相应的逻辑处理,JSP负责构造界面以及显示数据。

下面贴出代码,仅供参考,一些功能的具体实现在功能说明时有所介绍,只贴一些比较重要的部分的代码,大家主要重在理解。

此次项目,我感觉比较困难的部分是 加入购物车 部分和订单处理这部分。

加入购物车部分,一定要对集合操作非常熟悉才可以比较好的处理,另外还有合理的采用session,另外比较好的是构造一个BookShopping实体来帮助我们处理购物车部分的计算价格问题;

订单处理部分,生成订单,就是根据购物车里的有关书的一些信息,将这些信息插入order表中,会自动生成一个订单编号,因为当前购物车订单号相同;

生成订单,由book表、order表拼凑成items表;

生成历史订单,是根据当前登录用户在Order表中查找到此用户所有的订单号,再根据订单号在items表中查到所有的订单详情。

注册功能

 

 

package com.mm.Dao.impl;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.mm.Dao.UserDao;import com.mm.Utils.JDBCUtils;import com.mm.bean.User;//Dao层   数据库接口层public class UserDaoImpl implements UserDao {    public boolean addUser(User user) {        // TODO Auto-generated method stub        Connection con = null;        PreparedStatement ps = null;        ResultSet rs = null;        try {            String sql = "insert into user values(?,?,?,?)";                        con = JDBCUtils.getconnection();            ps = con.prepareStatement(sql);                        ps.setString(1, user.getUsername());            ps.setString(2, user.getPassword());            ps.setString(3, user.getEmail());            ps.setString(4, user.getAddress());                        int count = ps.executeUpdate();            System.out.print("受影响的行数是:"+count);                return true;        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            JDBCUtils.release(rs, ps, con);        }                return false;    }    public User findUser(String name, String password) {        // TODO Auto-generated method stub        Connection con = null;        PreparedStatement ps = null;        ResultSet rs = null;        User user = new User();                String sql = "select * from user where username = ? and password = ?";        try {            con = JDBCUtils.getconnection();            ps = con.prepareStatement(sql);            ps.setString(1, name);            ps.setString(2, password);                    rs = ps.executeQuery();            while(rs.next()){                try {                    user.setUsername(rs.getString("username"));                    user.setPassword(rs.getString("password"));                    user.setEmail(rs.getString("email"));                    user.setAddress(rs.getString("address"));                    return user;                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }finally{                    JDBCUtils.release(rs, ps, con);                }                                            }                    } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            JDBCUtils.release(rs, ps, con);        }                 return null;        }    }
1 //这层可以不要,将它归并到servlet里。 package com.mm.service.impl; 2  3 import com.mm.Dao.UserDao; 4 import com.mm.Dao.impl.UserDaoImpl; 5 import com.mm.bean.User; 6 import com.mm.service.UserService; 7  8 public class UserServiceImpl implements UserService { 9 10     public User login(String username, String password) {11         // TODO Auto-generated method stub12         UserDao dao = new UserDaoImpl();13         User user = dao.findUser(username, password);        14         return user;15     }16 17     public boolean register(User user) {18         // TODO Auto-generated method stub19         UserDao dao = new UserDaoImpl();20         if(dao.addUser(user)){21             return true;22         }23         return false;24         25     }26 27 }
1 package com.mm.servlet; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.HashMap; 6 import java.util.Map; 7  8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet;10 import javax.servlet.http.HttpServletRequest;11 import javax.servlet.http.HttpServletResponse;12 13 import com.mm.Dao.UserDao;14 import com.mm.Dao.impl.UserDaoImpl;15 import com.mm.bean.User;16 import com.mm.service.UserService;17 import com.mm.service.impl.UserServiceImpl;18 19 20 21 public class RegisterServlet extends HttpServlet {22 23     public void doGet(HttpServletRequest request, HttpServletResponse response)24             throws ServletException, IOException {25       doPost(request,response);26     27     }28 29     30       Map
errors = new HashMap
();31 public void doPost(HttpServletRequest request, HttpServletResponse response)32 throws ServletException, IOException { 33 //获取参数值34 String username = request.getParameter("username");35 String password = request.getParameter("password");36 String repassword = request.getParameter("repassword");37 String email = request.getParameter("email");38 String address = request.getParameter("address");39 40 //组装成一个user对象41 User user = new User();42 user.setUsername(username);43 user.setPassword(password);44 user.setEmail(email); 45 user.setAddress(address);46 //调用dao 来注册47 UserService dao = new UserServiceImpl();48 boolean re = dao.register(user);49 50 //根据注册结果来跳转 51 if(re){52 request.getRequestDispatcher("register_success.jsp").forward(request, response);53 }54 55 }else{56 request.setAttribute("errors", errors);57 request.getRequestDispatcher("register.jsp").forward(request, response);58 }59 60 } 65 }66 67 68
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 Map
errors = (HashMap
)request.getAttribute("errors"); 6 %> 7 8 9 10 11
12 13
注册页面14 15
16
17 18
35 36 37 38 39
47
48
49

欢迎注册北大青鸟网上书城

50
51
52
    53
  • 1.填写注册信息
  • 54
  • 2.注册成功
  • 55
56
57
58
59
用 户 名:
60
${errors.username }
61
密  码:
62
${errors.password}
63
确认密码:
64
${errors.repassword }
65
Email地址:
66
${errors.email }
67
通信地址:
68
69
70
71
72
73
74
78 79

 

 

登录功能

登录功能用到cookie会话技术,可以回显用户名密码;前提是复选框要选中

 

1 package com.mm.servlet; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 5  6 import javax.mail.Session; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.Cookie; 9 import javax.servlet.http.HttpServlet;10 import javax.servlet.http.HttpServletRequest;11 import javax.servlet.http.HttpServletResponse;12 import javax.servlet.http.HttpSession;13 14 import com.mm.bean.User;15 import com.mm.service.UserService;16 import com.mm.service.impl.UserServiceImpl;17 18 public class LoginServlet extends HttpServlet {19 20     21     public void doGet(HttpServletRequest request, HttpServletResponse response)22             throws ServletException, IOException {23               //得到页面输入的用户名和密码24                 String username = request.getParameter("username");25                 String password = request.getParameter("password");26                 String remember = request.getParameter("remember");27                 //从数据库中查找是否存在28                 UserService us = new UserServiceImpl();29                 User user = us.login(username, password);        30                 //找到 显示登陆成功,跳转到 User主页,跳转不成功,在login.jsp31                 //user不为空说明此用户真实存在32                 if(user != null){33                     //如果用户找到了,那就说明是合法用户34                     //把用户放入cookies中35                     Cookie cookie = new Cookie("username",username);36                     Cookie cookie1 = new Cookie("password",password);37                     if("on".equals(remember)){ 38                         cookie.setMaxAge(300);39                         cookie1.setMaxAge(300);40                     }else{41                         cookie.setMaxAge(0);42                         cookie1.setMaxAge(0);43                     }44                                         45                     response.addCookie(cookie);46                     response.addCookie(cookie1);47                     48                     //此用户存到session中49                     request.getSession().setAttribute("username", username);50                     51                     52                     response.setHeader("refresh", "3;url=BookServlet?op=list");53                     54                 }else{
//非法用户55 request.setAttribute("error", "用户名或密码错误");56 57 request.getRequestDispatcher("login.jsp").forward(request, response);58 59 60 }61 62 63 }64 65 66 public void doPost(HttpServletRequest request, HttpServletResponse response)67 throws ServletException, IOException {68 doGet(request,response);69 70 }71 72 }

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>              登录界面    
<% //拿到错误信息 String name = (String) request.getAttribute("error") ; if(name != null) out.write("
" + name + "") ; String username = "" ; String password = "" ; //拿到客户端携带的所有的Cookie Cookie[] cs = request.getCookies() ; //循环判断,如果拿到cookies for (int i = 0; cs !=null && i < cs.length; i++) { Cookie c = cs[i] ; if(c.getName().equals("username")){ //说明找到了存储用户名的cookie username = c.getValue() ; } if(c.getName().equals("password")){ //说明找到了存储密码的Cookie password = c.getValue() ; } } %>

用户登陆

用户名:
${error}
密 码:
是否记住此用户

 

 

注销功能

登录时将此用户存入session中,方便后边的使用;注销时将此用户从session中删除即可。

 

1 HttpSession se = request.getSession(false);2 if(se==null) {3 response.sendRedirect("login.jsp");4 return ; 5 }6 7 se.removeAttribute("username");8 response.sendRedirect("login.jsp");

 

 

 

加入购物车功能

方便对购物车进行管理,创建了一个购物车的实体,计算出了每种书花费的价格

 

1 package com.mm.bean; 2  3 public class BookShopping { 4     private Book book; 5     private int count;//购买的数量 6     private double totalprice;//总价格 7     public BookShopping(Book book , int count) { 8         this.book = book; 9         this.count = count;10         this.totalprice = this.book.getBookprice()*this.count;11     }12     public Book getBook() {13         return book;14     }15     public void setBook(Book book) {16         this.book = book;17     }18     19     public int getCount() {20         return count;21     }22     public void setCount(int count) {23         this.count = count;24     }25     public double getTotalprice() {26         return totalprice;27     }28     public void setTotalprice(double totalprice) {29         this.totalprice = totalprice;30     }31 32 33 }
BookShopping实体类

 

 

 

1 package com.mm.servlet; 2  3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import java.util.Set; 8  9 import javax.servlet.ServletException;10 import javax.servlet.http.HttpServlet;11 import javax.servlet.http.HttpServletRequest;12 import javax.servlet.http.HttpServletResponse;13 import javax.servlet.http.HttpSession;14 15 import com.mm.Dao.impl.BookDaoImpl;16 import com.mm.bean.Book;17 18 public class AddCartServlet extends HttpServlet {19 20     21     public void doGet(HttpServletRequest request, HttpServletResponse response)22             throws ServletException, IOException {23          doPost(request,response);24     }25       26     //将从User首页选中的加入购物车,还要根据书的本数还要计算价格27     public void doPost(HttpServletRequest request, HttpServletResponse response)28             throws ServletException, IOException {29 //从界面拿到选中的即需要加入购物车的所有图书的Id号30         String[] bookIds =(String[])request.getParameterValues("bookid");31         Map
bookMap = (Map
) request.getSession().getAttribute("bookMap");32 if(bookMap==null) bookMap = new HashMap();33 //遍历选择的商品34 if(bookIds!=null&&bookIds.length>0){35 for(String bookId: bookIds){36 //添加到购物车37 Integer count = bookMap.get(bookId);//得到bookid对应的数量38 if(count==null) bookMap.put(bookId, 1);39 else{40 bookMap.put(bookId, count+1);41 }42 }43 }44 45 //将购物车里书的id及选购的本数放入sesssion中, request.getSession().setAttribute("bookMap",bookMap); 46 47 request.getRequestDispatcher("goon.jsp").forward(request, response);48 }49 50 }
加入购物车的servlet

 

1 <%@ page language="java" import="java.util.*,com.mm.bean.*,com.mm.Dao.*,com.mm.Dao.impl.*" pageEncoding="UTF-8"%>  2 <%@ taglib prefix = "c"  uri = "http://java.sun.com/jsp/jstl/core"%>  3 <%  4 String path = request.getContextPath();  5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  6   7 Map
bookMap =(Map
)request.getSession().getAttribute("bookMap"); 8 BookDao dao = new BookDaoImpl(); 9 Iterator keys = bookMap.keySet().iterator(); 10 double hj = 0; 11 List
list = new ArrayList(); 12 while(keys.hasNext()){ 13 String key = (String)keys.next();//book的id 14 Book book = dao.findbookById(Integer.parseInt(key)); 15 int count = bookMap.get(key); 16 BookShopping bs = new BookShopping(book,count);//bookshopping里的构造函数,把价格算出来了。 17 hj+=bs.getTotalprice();//算总的合计,累计叠加 18 list.add(bs); 19 } 20 21 request.getSession().setAttribute("bookshoppinglist",list); 22 23 24 String username = (String)request.getSession().getAttribute("username"); 25 26 %> 27 28 29 30 31
32 33
购物车界面 34
35
36
38 39 40 41 42
58
59
60
61
73
62
63
64
65
66
67
68
69 70
71 72
74
75
76
77
78
79
80
81 82 83
图片预览 库存 书名 数量 单价 总价
${obj.book.bookimg} ${obj.book.booksave} ${obj.book.bookname} ${obj.count } ${obj.book.bookprice } ${obj.totalprice }
84 85 86
87

总价:¥<%=hj %>

88
返回继续购物 89
90
91 92
93
94
95
99 100
加入购物车的jsp显示与处理

主要用到EL,JSTL简化编程

 

生成订单功能

 

1 package com.mm.Dao.impl; 2  3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7  8 import com.mm.Dao.OrderDao; 9 import com.mm.Utils.JDBCUtils;10 import com.mm.bean.Orders;11 12 public class OrderDaoImpl implements OrderDao {13   //向数据库order表中插入一行数据,oid自增,可以自动生成oid14     public int addNewOrder(Orders order) {15         Connection con  = null ;16         PreparedStatement ps = null;17         ResultSet rs = null;18         int oid = 0;19         String sql = "insert  into orders(date,user_name,state,totalmoney) values(?,?,?,?)";20         try {21             con = JDBCUtils.getconnection();22             ps = con.prepareStatement(sql);23             ps.setString(1, order.getDate());24             ps.setString(2, order.getUser_name());25             ps.setInt(3, order.getState());26             ps.setDouble(4, order.getTotalmoney());27             int count = ps.executeUpdate();28             System.out.println("受影响的行数是:"+count);29             if(count == 1){30                 String s = "select oid from orders where date = ? and user_name = ? and state = ? and totalmoney = ?";31                 ps = con.prepareStatement(s);32                 ps.setString(1,order.getDate());33                 ps.setString(2, order.getUser_name());34                 ps.setInt(3,order.getState());35                 ps.setDouble(4, order.getTotalmoney());36                 rs = ps.executeQuery();37                 while(rs.next()){38                     oid = rs.getInt(1);//返回第一条记录39                 }                                40             }41         42             return oid;43         } catch (SQLException e) {44             // TODO Auto-generated catch block45             e.printStackTrace();46         }finally{47             JDBCUtils.release(rs, ps, con);48         }49         return oid;        50     }51     52     53     public static void main(String args[]){54         OrderDao d = new OrderDaoImpl();55         Orders o = new Orders();56         o.setDate("2016-09-09");57         o.setState(1);58         o.setUser_name("mxn");59         o.setTotalmoney(23);60         61         int a  = d.addNewOrder(o);62         System.out.println(a);63     }64 65 }
生成订单的DAO层

 

 

 

1 package com.mm.servlet;  2   3 import java.io.IOException;  4 import java.text.SimpleDateFormat;  5 import java.util.ArrayList;  6 import java.util.Date;  7 import java.util.Iterator;  8 import java.util.List;  9 import java.util.Map; 10 import java.util.Set; 11  12 import javax.servlet.ServletException; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16  17 import com.mm.Dao.OrderDao; 18 import com.mm.Dao.impl.ItemDAOImp; 19 import com.mm.Dao.impl.OrderDaoImpl; 20 import com.mm.bean.Book; 21 import com.mm.bean.BookShopping; 22 import com.mm.bean.ItemsIn; 23 import com.mm.bean.Orders; 24  25 public class OrderServlet extends HttpServlet { 26  27      28     public void doGet(HttpServletRequest request, HttpServletResponse response) 29             throws ServletException, IOException { 30        doPost(request,response); 31          32     } 33  34      35     public void doPost(HttpServletRequest request, HttpServletResponse response) 36             throws ServletException, IOException { 37          38          String op = request.getParameter("op"); 39           40          if(op==null)  op="list"; 41          if("list".equals(op)){ 42              43              String username = (String)request.getSession().getAttribute("username");                           44              int state = 1;  45              String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); 46              System.out.println("时间是"+date); 47              Orders order = new Orders(); 48              order.setDate(date); 49              order.setState(state); 50              order.setUser_name(username); 51              //order.setTotalmoney(totalmoney);          52              OrderDao dao = new OrderDaoImpl();//根据一行数据就可以得到订单的oid; 53              int oid = dao.addNewOrder(order);//从Order表中根据order的其他信息得到order的oid    ;         54              System.out.println("生成的订单编号是"+oid); 55               56               57              List
li = new ArrayList(); 58 //得到bookshopping 集合 59 List
list = (List
) request.getSession().getAttribute("bookshoppinglist"); 60 if(list!=null){ 61 Iterator
it = list.iterator(); 62 while(it.hasNext()){ 63 BookShopping bs = it.next(); 64 bs.getBook();//得到图书实体 65 bs.getCount();//得到图书对应的本书 66 67 System.out.println("图书对应的本数:"+bs.getCount()); 68 69 70 ItemsIn in = new ItemsIn(); 71 in.setBook_id(bs.getBook().getBookid()); 72 in.setNumber(bs.getCount()); 73 in.setO_id(oid); 74 in.setSinglePrice(bs.getBook().getBookprice()); 75 in.setSumMoney(bs.getTotalprice()); 76 77 li.add(in); 78 79 } 80 81 ItemDAOImp d = new ItemDAOImp(); 82 int c = d.insertItem(li); 83 System.out.println(" :"+c); 84 }else{ 85 System.out.println("list为null"); 86 } 87 88 89 90 request.getSession().setAttribute("oid",oid ); 91 response.sendRedirect("shopping-success.html"); 92 93 94 } 95 96 97 98 } 99 100 }
生成订单的servlet

 

 

订单显示功能  &  查看历史订单

 

 

1 package com.mm.Dao.impl;  2   3 import java.sql.Array;  4 import java.sql.Connection;  5 import java.sql.Date;  6 import java.sql.PreparedStatement;  7 import java.sql.ResultSet;  8 import java.sql.SQLException;  9 import java.text.SimpleDateFormat; 10 import java.util.ArrayList; 11 import java.util.List; 12  13 import com.mm.Dao.IItemDAO; 14 import com.mm.Utils.JDBCUtils; 15 import com.mm.bean.ItemsIn; 16 import com.mm.bean.ItemsOut; 17  18 public class ItemDAOImp implements IItemDAO {     19     Integer oid = 1; 20     public Integer getOid() { 21         return oid; 22     } 23     public void setOid(Integer oid) { 24         this.oid = oid; 25     } 26  27  28     // 找到某页的订单详情数据 29     public List
getPageList(int currentPage, int count) { 30 31 32 Connection con = null; 33 PreparedStatement ps = null; 34 ResultSet rs = null; 35 List
list = new ArrayList(); 36 try { 37 String sql = "SELECT bookname,state,oid,DATE,user_name,summoney,bookimg,singleprice,number FROM book,orders,items WHERE items.o_id = orders.oid AND items.book_id=book.bookid AND orders.oid="+oid+" limit ?,?"; 38 con = JDBCUtils.getconnection(); 39 ps = con.prepareStatement(sql); 40 //ps.setInt(1, oid); 41 ps.setInt(1, (currentPage - 1) * count);// 某页的起始数据 42 ps.setInt(2, count);// 每页显示的数据数 43 rs = ps.executeQuery(); 44 while (rs.next()) { 45 list.add(toitem(rs)); 46 } 47 return list; 48 } catch (SQLException e) { 49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 } finally { 52 JDBCUtils.release(rs, ps, con); 53 } 54 return null; 55 } 56 57 58 String username = "mxn"; 59 // 根据姓名,获取到此姓名订单的所有数据,并分页显示。 60 public List
getPageList1(int currentPage, int count) { 61 62 Connection con = null; 63 PreparedStatement ps = null; 64 ResultSet rs = null; 65 List
list = new ArrayList(); 66 List
l = new ArrayList(); 67 // 根据姓名,从order表中先获取到此用户所有的订单号! 68 String sql1 = "select oid from orders where user_name = ?"; 69 try { 70 con = JDBCUtils.getconnection(); 71 ps = con.prepareStatement(sql1); 72 ps.setString(1, username); 73 rs = ps.executeQuery(); 74 int i=0; 75 while (rs.next()) { 76 list.add((Integer)rs.getInt("oid")); 77 //System.out.println("list[新加的值是]"+list.get(i)); 78 i++; 79 } 80 String in=""; 81 for (int j = 0; j < list.size()-1; j++) { 82 in=in+list.get(j)+","; 83 } 84 in+=list.get(list.size()-1); 85 // System.out.println("in---------------"+in); 86 //根据订单号从多张表中查找到需要显示的订单数据 87 String sql = "SELECT bookname,state,oid,DATE,user_name,summoney,bookimg,singleprice,number FROM book,orders,items WHERE items.o_id = orders.oid AND items.book_id=book.bookid AND orders.oid in("+in+") limit ?,?"; 88 ps = con.prepareStatement(sql); 89 ps.setInt(1, (currentPage - 1) * count);// 某页的起始数据 90 ps.setInt(2, count);// 每页显示的数据数 91 rs = ps.executeQuery(); 92 while (rs.next()) { 93 l.add(toitem(rs)); 94 } 95 return l; 96 } catch (SQLException e) { 97 // TODO Auto-generated catch block 98 e.printStackTrace(); 99 }finally{100 JDBCUtils.release(rs, ps, con);101 }102 103 return null; 104 }105 106 107 private ItemsOut toitem(ResultSet rs) {108 ItemsOut io = new ItemsOut();109 try {110 io.setBookimg(rs.getString("bookimg"));111 io.setBookname(rs.getString("bookname"));112 io.setDate(rs.getString("date"));113 io.setNumber(rs.getInt("number"));114 io.setSinglePrice(rs.getDouble("singleprice"));115 io.setSumMoney(rs.getDouble("summoney"));116 io.setUsername(rs.getString("user_name"));117 io.setState(rs.getInt("state"));118 io.setO_id(rs.getInt("oid"));119 return io;120 } catch (SQLException e) {121 // TODO Auto-generated catch block122 e.printStackTrace();123 }124 125 return null;126 }127 128 public int getTotalcount() {129 Connection con = null;130 PreparedStatement ps = null;131 ResultSet rs = null;132 try {133 con = JDBCUtils.getconnection();134 ps = con.prepareStatement("select count(*) from items where items.o_id=3");135 rs = ps.executeQuery();136 if (rs.next()) {137 return rs.getInt(1);// 返回第一条记录138 }139 } catch (Exception e) {140 e.printStackTrace();141 } finally {142 JDBCUtils.release(rs, ps, con);143 }144 return 0;145 }146 147 public int getTotalcount1() {148 // TODO Auto-generated method stub149 int reCount=0;150 Connection con = null;151 PreparedStatement ps = null;152 ResultSet rs = null;153 String sql = "select oid from orders where user_name = ?"; 154 List
list = new ArrayList();155 try {156 con = JDBCUtils.getconnection();157 ps = con.prepareStatement(sql);158 ps.setString(1, username);159 rs = ps.executeQuery();160 int i=0;161 while (rs.next()) {162 list.add((Integer)rs.getInt("oid"));163 System.out.println("list[新加的值是]"+list.get(i));164 i++;165 } 166 String in="";167 for (int j = 0; j < list.size()-1; j++) {168 in=in+list.get(j)+",";169 }170 in+=list.get(list.size()-1);171 String sqlcont="select count(itemid) from items where items.o_id in("+in+")";172 ps = con.prepareStatement(sqlcont);173 rs = ps.executeQuery();174 if (rs.next()) {175 reCount=rs.getInt(1);176 }177 } catch (Exception e) {178 e.printStackTrace();179 } finally {180 JDBCUtils.release(rs, ps, con);181 }182 return reCount;183 }184 185 public String getUsername() {186 return username;187 }188 189 public void setUsername(String username) {190 this.username = username;191 }192 193 194 //向订单表中插入数据195 public int insertItem(List
list){196 Connection con = null;197 PreparedStatement ps = null;198 ResultSet rs = null ; 199 int c = 0 ; 200 for(ItemsIn in:list){201 String sql = "insert into items (o_id,summoney,singleprice,number,book_id) values(?,?,?,?,?);";202 try {203 con = JDBCUtils.getconnection();204 ps = con.prepareStatement(sql);205 ps.setInt(1, in.getO_id());206 ps.setDouble(2, in.getSumMoney());207 ps.setDouble(3, in.getSinglePrice());208 ps.setInt(4, in.getNumber()); 209 ps.setInt(5, in.getBook_id());210 211 System.out.println("eeeeeeeeeeeeeeeeeeeeeeee");212 c = ps.executeUpdate();213 System.out.println("所影响的行数是:"+c);214 215 if(c == 1){216 continue; //217 }else{218 break;219 } 220 } catch (SQLException e) {221 // TODO Auto-generated catch block222 e.printStackTrace();223 }finally{224 JDBCUtils.release(rs, ps, con);225 } 226 return c;227 }228 return c;229 230 231 232 }233 234 235 236 public static void main(String[] args) {237 // List
list = new ArrayList();238 ItemDAOImp id = new ItemDAOImp();239 // id.setUsername("ss");240 // List
list1 = id.getPageList1(1, 2);241 // int s = id.getTotalcount1();242 // System.out.println("总计路数666666666666666666666666666666----------"+s);243 // for (ItemsOut i : list1) {244 // System.out.println(i.getSumMoney());245 // }246 // 247 // System.exit(0);248 // }249 ItemsIn in = new ItemsIn();250 in.setBook_id(1);251 in.setNumber(2);252 in.setO_id(2);253 in.setSinglePrice(22);254 in.setSumMoney(23);255 List
list = new ArrayList();256 list.add(in);257 id.insertItem(list);258 }259 }
订单显示 和查看历史订单的dao层

 

 

 

1 package com.mm.servlet; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.List; 6 import java.util.Map; 7  8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet;10 import javax.servlet.http.HttpServletRequest;11 import javax.servlet.http.HttpServletResponse;12 13 import com.mm.Dao.impl.ItemDAOImp;14 import com.mm.bean.Book;15 import com.mm.bean.ItemsOut;16 import com.mm.bean.User;17 18 public class MyItemsServlet extends HttpServlet {19 20     21     public void doGet(HttpServletRequest request, HttpServletResponse response)22             throws ServletException, IOException {23          doPost(request,response);24     }25 26     27     public void doPost(HttpServletRequest request, HttpServletResponse response)28             throws ServletException, IOException {29        String op = request.getParameter("op");30        ItemDAOImp id = new ItemDAOImp();31        //从session中拿到oid32        id.setOid((Integer)request.getSession().getAttribute("oid"));33        34        35        //从session中拿到useranme36        id.setUsername((String)request.getSession().getAttribute("username"));37        38        39        if(op == null)  op = "list";40        //查看订单详情41        if("list".equals(op)){42             //接收 显示所有的请求信息        43           44            45              //从页面超链传来的 每页显示的数量count46              String count = request.getParameter("count");47              if(count == null)  count = "10";//默认每页10条48              String curpageIndex = request.getParameter("curpage");//得到当前页的索引49              if(curpageIndex == null)  curpageIndex = "1";//默认是首页50              //根据传来的参数 找到 当前页的数据集list51               List
list= id.getPageList(Integer.parseInt(curpageIndex), Integer.parseInt(count));52 53 //得到总的数据量54 int z = id.getTotalcount();55 56 //根据传来的参数得到总页数57 int pagenum = (z+Integer.parseInt(count)-1)/Integer.parseInt(count);58 59 //将得到的当前页的数据集、总页数、和当前页返回给页面,页面进行显示60 request.setAttribute("list", list);61 62 request.setAttribute("pagecount", pagenum);63 64 request.setAttribute("currentPageIndex",curpageIndex); 65 66 request.getRequestDispatcher("orderlist.jsp").forward(request, response);67 return ;68 69 70 }else if("find".equals(op)){
//查看历史订单71 72 String username = (String)request.getSession().getAttribute("username");73 if(username==null){74 response.sendRedirect("login.jsp");75 }else{76 //从页面超链传来的 每页显示的数量count77 String count = request.getParameter("count");78 if(count == null) count = "10";//默认每页10条79 String curpageIndex = request.getParameter("curpage");//得到当前页的索引80 if(curpageIndex == null) curpageIndex = "1";//默认是首页81 //根据传来的参数 找到 当前页的数据集list 82 List
list1= id.getPageList1(Integer.parseInt(curpageIndex), Integer.parseInt(count));83 //得到总的数据量 84 int z1 = id.getTotalcount1();85 //根据传来的参数得到总页数 86 int pagenum1 = (z1+Integer.parseInt(count)-1)/Integer.parseInt(count);87 //将得到的当前页的数据集、总页数、和当前页返回给页面,页面进行显示 88 request.setAttribute("list", list1); 89 request.setAttribute("pagecount", pagenum1);90 request.setAttribute("currentPageIndex",curpageIndex); 91 request.getRequestDispatcher("orderhistory.jsp").forward(request, response);92 return ;93 }94 }95 96 }97 98 }
分页显示订单和查看历史订单的servlet

 

 

 

1 <%@ page language="java"  2     import="java.util.*,com.mm.bean.*,com.mm.Dao.impl.*"  3     pageEncoding="UTF-8"%>  4 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  5 <%  6     String path = request.getContextPath();  7     String basePath = request.getScheme() + "://"  8             + request.getServerName() + ":" + request.getServerPort()  9             + path + "/"; 10  11     List
list = (ArrayList
) request.getAttribute("list"); 12 13 //总页数 14 Integer pagenum = (Integer) request.getAttribute("pagecount"); 15 16 17 //当前页 18 String curpageStr = (String) request.getAttribute("currentPageIndex"); 19 Integer curpage = Integer.parseInt(curpageStr); 20 21 22 String username = (String)request.getSession().getAttribute("username"); 23 %> 24 25 26 27 28
29
30
我的订单 31 32 33 34 35
56
57
58
72
59
60
61
62
63
64
65
66
67
68
69
70 71
73
74
75
76
77
78
79
80
81
82
83 84 85 86 87
订单编号 订单商品 订单名称 收货人 订单单价 购买量 订单金额 下单时间 订单状态
${item.o_id } ${item.bookname} ${item.username } ${item.singlePrice} ${item.number } ${item.sumMoney } ${item.date} ${item.state}
88
89 90
首页 91 92
93
94
上一页 95
96
97 <%if(curpage>1){ %> 98
上一页 99 100 <%} else{%>101
上一页102 103 <%} %>104
105
106 107
108
109
下一页110
111
112 113 <%if(curpage>=pagenum){ %>114
下一页115 116 <%} else {%>117
下一页118 119 <%} %>120
121
122
尾页123 124 125
126
127 128
查看历史订单129 130 131
132
133
134
135 136 137 138 139
分页显示订单JSP

 

1 <%@ page language="java"  2     import="java.util.*,com.mm.bean.*,com.mm.Dao.impl.*"  3     pageEncoding="UTF-8"%>  4 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  5 <%  6     String path = request.getContextPath();  7     String basePath = request.getScheme() + "://"  8             + request.getServerName() + ":" + request.getServerPort()  9             + path + "/"; 10  11     List
list = (ArrayList
) request.getAttribute("list"); 12 13 //总页数 14 Integer pagenum = (Integer) request.getAttribute("pagecount"); 15 16 17 //当前页 18 String curpageStr = (String) request.getAttribute("currentPageIndex"); 19 Integer curpage = Integer.parseInt(curpageStr); 20 21 String username = (String)request.getSession().getAttribute("username"); 22 %> 23 24 25 26 27
28
29
我的订单 30 31 32 33 34
55
56
57
71
58
59
60
61
62
63
64
65
66
67
68
69 70
72
73
74
75
76
77
78
79
80
81
82 83 84 85 86
订单编号 订单商品 订单名称 收货人 订单单价 购买量 订单金额 下单时间 订单状态
${item.o_id } ${item.bookname} ${item.username } ${item.singlePrice} ${item.number } ${item.sumMoney } ${item.date} ${item.state}
87
88 89
首页 90 91
92
93
上一页 94
95
96 <%if(curpage>1){ %> 97
上一页 98 99 <%} else{%>100
上一页101 102 <%} %>103
104
105 106
107
108
下一页109
110
111 112 <%if(curpage>=pagenum){ %>113
下一页114 115 <%} else {%>116
下一页117 118 <%} %>119
120
121
尾页122 123 124
125
126
128
130
查看历史订单131 132 133
134
135
136
137 138 139 140 141
查看历史订单JSP

 

分页显示图书信息功能

 

1 package com.mm.Dao.impl;  2   3 import java.sql.Connection;  4 import java.sql.PreparedStatement;  5 import java.sql.ResultSet;  6 import java.sql.SQLException;  7 import java.util.ArrayList;  8 import java.util.List;  9  10 import com.mm.Dao.BookDao; 11 import com.mm.Utils.JDBCUtils; 12 import com.mm.bean.Book; 13  14 public class BookDaoImpl implements BookDao { 15    //根据当前页的索引返回当前页的数据集合 16     public List
getPageList(int currentPageIndex, int count) { 17 // TODO Auto-generated method stub 18 19 Connection con = null; 20 PreparedStatement ps = null; 21 ResultSet rs = null; 22 List
list = new ArrayList(); 23 try { 24 con = JDBCUtils.getconnection(); 25 ps = con.prepareStatement("select * from book limit ?,?"); 26 ps.setInt(1, (currentPageIndex-1)*count); 27 ps.setInt(2, count); 28 rs = ps.executeQuery(); 29 while(rs.next()){ 30 list.add(tobook(rs)); 31 } 32 return list; 33 } catch (SQLException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 }finally{ 37 JDBCUtils.release(rs, ps, con); 38 } 39 return null; 40 } 41 42 private Book tobook(ResultSet rs) { 43 // TODO Auto-generated method stub 44 Book b = new Book(); 45 try { 46 b.setBookid(rs.getInt("bookid")); 47 b.setBookname(rs.getString("bookname")); 48 b.setBookpublish(rs.getString("bookpublish")); 49 b.setBookprice(rs.getDouble("bookprice")); 50 b.setBookauthor(rs.getString("bookauthor")); 51 b.setBookcontent(rs.getString("bookcontent")); 52 b.setBookimg(rs.getString("bookimg")); 53 b.setBooksave(rs.getString("booksave")); 54 } catch (SQLException e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 } 58 return b; 59 } 60 61 //返回数据库中图书总数,在Servlet可以算出总的页数 62 public int getTotalcount() { 63 // TODO Auto-generated method stub 64 65 Connection con = null; 66 PreparedStatement ps = null; 67 ResultSet rs = null; 68 try { 69 con = JDBCUtils.getconnection(); 70 ps = con.prepareStatement("select count(*) from book"); 71 rs = ps.executeQuery(); 72 if(rs.next()){ 73 return rs.getInt(1);//返回第一条记录 74 } 75 }catch(Exception e){ 76 e.printStackTrace(); 77 }finally{ 78 JDBCUtils.release(rs, ps, con); 79 } 80 81 82 return 0; 83 } 84 //模糊查询,根据书名返回符合的图书集合 85 public List
findbookByName(String bookname) { 86 // TODO Auto-generated method stub 87 Connection con = null; 88 PreparedStatement ps = null; 89 ResultSet rs = null; 90 Book b = new Book(); 91 List
li = new ArrayList(); 92 try { 93 con = JDBCUtils.getconnection(); 94 String qbk="%"+bookname+"%"; 95 //System.out.println(qbk); 96 String sql="select * from book where bookname like ?"; 97 ps = con.prepareStatement(sql); 98 ps.setString(1,qbk); 99 rs = ps.executeQuery();100 while(rs.next()){101 li.add(tobook(rs));102 103 } 104 return li;105 } catch (SQLException e) {106 // TODO Auto-generated catch block107 e.printStackTrace();108 }finally{109 JDBCUtils.release(rs, ps, con);110 } 111 return null;112 }113 //根据ID号找到书的详细信息114 public Book findbookById(int bid) {115 // TODO Auto-generated method stub116 Connection con = null;117 PreparedStatement ps = null;118 ResultSet rs = null; 119 Book book = new Book();120 try {121 con = JDBCUtils.getconnection();122 String sql = "select * from book where bookid =?"; 123 ps = con.prepareStatement(sql);124 ps.setInt(1, bid);125 rs = ps.executeQuery();126 while(rs.next()){127 return tobook(rs);128 }129 130 } catch (SQLException e) {131 // TODO Auto-generated catch block132 e.printStackTrace();133 }finally{134 JDBCUtils.release(rs, ps, con);135 } 136 return null;137 }138 139 }show
分页显示图书servlet层的处理

 

1 package com.mm.servlet; 2  3 import java.io.IOException; 4 import java.util.List; 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 12 import com.mm.bean.Book;13 import com.mm.service.BookService;14 import com.mm.service.impl.BookServiceImpl;15 16 public class BookServlet extends HttpServlet {17 18     BookService bs = new BookServiceImpl();19     20     public void doGet(HttpServletRequest request, HttpServletResponse response)21             throws ServletException, IOException {22             doPost(request,response);23     }24 25 26     public void doPost(HttpServletRequest request, HttpServletResponse response)27             throws ServletException, IOException {28         29       String op = request.getParameter("op");30      31       32       if(op==null)    op = "list";33       //分页显示book表中的所有图书34       if("list".equals(op)){        35           //从页面超链传来的 每页显示的数量count36           String count = request.getParameter("count");37           if(count == null)  count = "10";//默认每页10条38           String curpageIndex = request.getParameter("curpage");//得到当前页的索引39           if(curpageIndex == null) curpageIndex = "1";//默认是首页40           //根据传来的参数 找到 当前页的数据集list41            List
list= bs.getPageList(Integer.parseInt(curpageIndex), Integer.parseInt(count));42 43 //根据传来的参数得到总页数44 int pagenum = bs.Pagecount(Integer.parseInt(count));45 //将得到的当前页的数据集、总页数、和当前页返回给页面,页面进行显示46 request.setAttribute("list", list);47 request.setAttribute("pagecount", pagenum);48 request.setAttribute("currentPageIndex",curpageIndex );49 50 request.getRequestDispatcher("showbook.jsp").forward(request, response);51 return ;52 53 }else if("find".equals(op)){54 //模糊查询55 //从页面超链得到每页显示的数目56 String bookname = request.getParameter("bookname");57 String count = request.getParameter("count");58 if(count == null) count = "10";//默认每页10条 59 List
book = bs.findbookByName(bookname);//根据书名找到书的集合60 request.setAttribute("list", book);61 request.getRequestDispatcher("showbook.jsp").forward(request, response);62 return ;63 } 64 65 }66 67 68 }
图书显示JSP

 

转载于:https://www.cnblogs.com/mengxiao/p/5827409.html

你可能感兴趣的文章
TOJ 3046: 招商银行网络系统
查看>>
java8_api_正则表达式
查看>>
java匿名对象
查看>>
RichTextBox.MouseWheel事件控制父控件Panel的内容滚动
查看>>
php程序在浏览器哪里判断,一个判断PHP程序是否被同时在不同浏览器上执行的问题...
查看>>
php 获取5分钟前,php时间轴开发,即显示为“刚刚”、“5分钟前”、“昨天12:10...
查看>>
php ob_end_clean(),ob_end_clean(): failed to delete buffer-ThinkPHP 5.1.23
查看>>
ecshop send.php on line 71,ECSHOP调用指定DEDECMS织梦栏目文章列表
查看>>
linux 怎么运行多个target,radhat7下使用targetcli为多个启动器配置iSCSI访问控制
查看>>
c语言2015实验答案,2015年计算机二级《C语言》精选练习题及答案(15)
查看>>
c语言中word16,(word)16道嵌入式C语言面试题.doc
查看>>
c语言雷克子波,vans.c · skateboi/雷克子波与一维数组卷积的图像 - Gitee.com
查看>>
c语言ctrl c线程中动态申请的内存,【C++】 外传篇 3_动态内存申请的结果
查看>>
android textview显示不下,Android TextView不显示我的所有文本
查看>>
android手机之间tcp通信,Android 设备间通信方式
查看>>
数据库集群系统研究系列(2)-现存的数据库的解决方案的原理解析
查看>>
Racktables自定义报表
查看>>
网摘是否影响网络推广和SEO
查看>>
Outlook中轻松添加LDAP服务
查看>>
统一沟通-技巧-2-Lync 2010-照片-无显示-组织-显示-为-自己
查看>>