澳门新葡萄京娱乐场jsp servlet分页代码示例

    public BigDecimal getDeptno() {
        return deptno;
    }

复制代码 代码如下:

网络书城项目,javaweb网络书城项目

   
实习将在截至了,最终要上交的是网络书城项目和大器晚成份文书档案。接下来简介一下连串。

项目是根据三层结构来写,数据访谈层(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 stub
12         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 stub
19         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<String, String> errors = new HashMap<String, String>();
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<String,String> errors  = (HashMap<String,String>)request.getAttribute("errors");
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>注册页面</title>
14     
15 <link type="text/css" rel="stylesheet" href="css/style.css" />
16 <script type="text/javascript" src="jquery.js"></script>
17 
18 <script type="text/javascript">
19 function validate(){
20   var username = document.getElementById("user1").value;
21    var password = document.getElementById("pwd1").value;
22     var repassword = document.getElementById("rpwd1").value;
23      var email = document.getElementById("email1").value;
24       var address = document.getElementById("address1").value;
25       var reg1 = /[a-zA-Z]w*/;
26       var reg2 = /w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*/;
27       if(username.length<=0)  alert("用户名不能为空!");
28       else if(!reg1.test(username)) alert("用户名格式不正确!");
29       else if(password.length<6) alert("密码长度必须大于等于6");
30       else if(password!=repassword) alert("两次密码不一致!");
31       else if(!reg2.test(email)) alert("邮箱格式不正确!!");
32       else document.form[1].submit();
33 }
34 </script>
35 
36   </head>
37   
38   <body>39     <div id="header" class="wrap">
40     <div id="logo">北大青鸟网上书城</div>
41     <div id="navbar">
42         <form method="get" name="search" action="">
43             搜索:<input class="input-text" type="text" name="keywords" /><input class="input-btn" type="submit" name="submit" value="" />
44         </form>
45     </div>
46 </div>
47 <div id="register">
48     <div class="title">
49         <h2>欢迎注册北大青鸟网上书城</h2>
50     </div>
51     <div class="steps">
52         <ul class="clearfix">
53             <li class="current">1.填写注册信息</li>
54             <li class="unpass">2.注册成功</li>
55         </ul>
56     </div>
57     <form method="post" action="RegisterServlet" id="registerForm">
58     <dl>
59             <dt>用 户 名:</dt>
60             <dd><input id = "user1"  class="input-text" type="text" name="username" />${errors.username }</dd>
61             <dt>密  码:</dt>
62             <dd><input id = "pwd1" class="input-text" type="password" name="password" />${errors.password}</dd>
63             <dt>确认密码:</dt>
64             <dd><input id = "rpwd1" class="input-text" type="password" name="repassword" />${errors.repassword }</dd>
65             <dt>Email地址:</dt>
66             <dd><input id = "email1"  class="input-text" type="text" name="email" />${errors.email }</dd>
67             <dt>通信地址:</dt>
68             <dd><input id = "address1" class="input-text" type="text" name="address" /></dd>
69             <dt></dt>
70             <dd class="button"><input class="input-reg" type="submit" name="register"  onClick="validate()"/></dd>
71         </dl>
72     </form>
73 </div>
74 <div id="footer" class="wrap">
75     北大青鸟网上书城 &copy; 版权所有
76 
77 </div>
78   </body>
79 </html>

 

 

登陆功用

签到效率用到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.jsp
31                 //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+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>登录界面</title>
    <link type="text/css" rel="stylesheet" href="css/style.css" />


  </head>

  <body>class="wrap">
    <div id="logo">北大青鸟网上书城</div>
    <div id="navbar">
        <form method="get" name="search" action="">
            搜索:<input class="input-text" type="text" name="keywords" />
                 <input class="input-btn" type="submit" name="submit" value="" />
        </form>
    </div>
</div>
<div id="login">
<%
        //拿到错误信息
        String name = (String) request.getAttribute("error") ;
        if(name != null)
             out.write("<font color = red>" + name + "</font>") ;

        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() ;
                }
        }


 %>



    <h2>用户登陆</h2>
    <form method="post" action="LoginServlet">
        <dl>
            <dt>用户名:  </dt>
            <dd><input class="input-text" type="text"  name="username"  value = "<%=username %>"/>${error}</dd>
            <dt>密 码:  </dt>
            <dd><input class="input-text" type="password" name="password"   value = "<%=password%>"/></dd>
            <dt><input class = "input-text" type= "checkbox"  name = "remember"  value = "on"/></dt>
            <dd>是否记住此用户</dd>
            <dt></dt>
            <dd class="button"><input class="input-btn" type="submit" name="submit" value="" />
            <input class="input-reg" type="button" name="register" value="" onclick="window.location='register.jsp';" /></dd>
        </dl>
    </form>
</div>
<div id="footer" class="wrap">
    北大青鸟网上书城 &copy; 版权所有

</div>
  </body>
</html>

 

 

撤废成效

登陆时将此客户存入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 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实体类

 

 

 

澳门新葡萄京娱乐场 2 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 responseState of Qatar 22
throws ServletException, IOException { 23 doPost(request,responseState of Qatar; 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”State of Qatar; 31
Map<String,Integer> bookMap = (Map<String, Integer>卡塔尔国request.getSession(卡塔尔.getAttribute(“bookMap”卡塔尔; 32 if(bookMap==null卡塔尔国bookMap = new HashMap(卡塔尔; 33 //遍历选拔的商品 34
if(bookIds!=null&&bookIds.length>0State of Qatar{ 35 for(String bookId: bookIds卡塔尔国{
36 //增加到购物车 37 Integer count =
bookMap.get(bookIdState of Qatar;//得到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”,bookMapState of Qatar; 46 47
request.getRequestDispatcher(“goon.jsp”卡塔尔国.forward(request, response卡塔尔(قطر‎; 48
} 49 50 } 插手购物车的servlet

 

澳门新葡萄京娱乐场 3 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 =
“; 3 <% 4 String path =
request.getContextPath(卡塔尔(قطر‎; 5 String basePath =
request.getScheme(State of Qatar+”://”+request.getServerName(卡塔尔国+”:”+request.getServerPort(卡塔尔+path+”/”;
6 7 Map<String,Integer> bookMap
=(Map<String,Integer>卡塔尔国request.getSession(State of Qatar.getAttribute(“bookMap”卡塔尔(قطر‎;
8 BookDao dao = new BookDaoImpl(State of Qatar; 9 Iterator keys =
bookMap.keySet(卡塔尔.iterator(卡塔尔(قطر‎; 10 double hj = 0; 11
List<BookShopping> list = new ArrayList(卡塔尔; 12
while(keys.hasNext(State of Qatar卡塔尔{ 13 String key = (StringState of Qatarkeys.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”,listState of Qatar; 22 23 24
String username = (String卡塔尔request.getSession(卡塔尔.getAttribute(“username”卡塔尔国;
25 26 %> 27 28 <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01
Transitional//EN”> 29 <html> 30 <head> 31 <base
href=”<%=basePath%>”> 32 33
<title>购物车界面</title> 34 <link type=”text/css”
rel=”stylesheet” href=”css/style.css” /> 35 <script
type=”text/javascript” src = “jquery.js”></script> 36
<script type=”text/javascript”> 37 </script> 38 39
</head> 40 41 <body> 42 <div id=”header” class=”wrap”>
43 <div id=”logo”>武白色鸟网络书城</div> 44 <div
id=”navbar”> 45 <div class=”userMenu”> 46 <ul> 47
<li><a href=”showbook.jsp”>招待您:${username
}</a></li> 48 <li><a
href=”orderlist.jsp”>我的订单</a></li> 49 <li
class=”current”><a
href=”shopping.jsp”>购物车</a></li> 50 <li><a
href=”exit.jsp”>注销</a></li> 51 </ul> 52
</div> 53 <form method=”get” name=”search” action=””> 54
搜索:<input class=”input-text” type=”text” name=”keywords”
/><input class=”input-btn” type=”submit” name=”submit” value=””
/> 55 </form> 56 </div> 57 </div> 58 <div
id=”content” class=”wrap”> 59 <div class=”list bookList”> 60
<form method=”post” name=”shoping” action=”OrderServlet?op=list”>
61 <table> 62 <tr class=”title”> 63 <th
class=”view”>图片预览</th> 64 <th>仓库储存</th> 65
<th>书名</th> 66 <th class=”nums”>数量</th> 67
<th class=”nums”>单价</th> 68 <th
class=”price”>总价值</th> 69 70 </tr> 71 72 <c:forEach
var=”obj” items = “${bookshoppinglist}”> 73 <tr> 74
<td>${obj.book.bookimg}</td> 75
<td>${obj.book.booksave}</td> 76
<td>${obj.book.bookname}</td> 77 <td>${obj.count
}</td> 78 <td>${obj.book.bookprice }</td> 79
<td>${obj.totalprice }</td> 80 </tr> 81
</c:forEach> 82 83 </table> 84 85 86 <div
class=”button”> 87 <h4>总价值:¥<span><%=hj
%></span>元</h4> 88 <a
href=”BookServlet?op=list”>重返继续购物</a> 89 <input id =
“buy” class=”input-chart” type=”submit” name=”submit” value=”” /> 90
</div> 91 92 </form> 93 </div> 94 </div> 95
<div id=”footer” class=”wrap”> 96 哈工大青鸟网络书城 © 版权所有97 98 </div> 99 </body> 100 </html> 加入购物车的jsp呈现与管理

最主要用到EL,JSTL简化编制程序

 

转移订单作用

 

澳门新葡萄京娱乐场 4 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自增,能够自动生成oid 14 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(State of Qatar卡塔尔; 27 int
count = ps.executeUpdate(卡塔尔(قطر‎; 28
System.out.println(“受影响的行数是:”+count卡塔尔国; 29 if(count == 1State of Qatar{ 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(State of Qatar卡塔尔(قطر‎; 35
ps.setDouble(4, order.getTotalmoney(卡塔尔卡塔尔(قطر‎; 36 rs = ps.executeQuery(State of Qatar; 37
while(rs.next(卡塔尔State of Qatar{ 38 oid = rs.getInt(1卡塔尔(قطر‎;//再次来到第一条记录 39 } 40 } 41 42
return oid; 43 } catch (SQLException e卡塔尔(قطر‎ { 44 // TODO Auto-generated
catch block 45 e.printStackTrace(卡塔尔国; 46 }finally{ 47
JDBCUtils.release(rs, ps, conState of Qatar; 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层

 

 

 

澳门新葡萄京娱乐场 5 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(totalmoneyState of Qatar; 52
OrderDao dao = new OrderDaoImpl(卡塔尔国;//依照风流罗曼蒂克行数据就可以收获订单的oid; 53
int oid =
dao.addNewOrder(order卡塔尔(قطر‎;//从Order表中根据order的别样信息获得order的oid ;
54 System.out.println(“生成的订单号码是”+oidState of Qatar; 55 56 57
List<ItemsIn> li = new ArrayList(卡塔尔; 58 //获得bookshopping 会集 59
List<BookShopping> list = (List<BookShopping>卡塔尔(قطر‎request.getSession(State of Qatar.getAttribute(“bookshoppinglist”State of Qatar; 60
if(list!=nullState of Qatar{ 61 Iterator<BookShopping> it = list.iterator(卡塔尔; 62
while(it.hasNext(State of Qatar卡塔尔国{ 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(liState of Qatar; 83
System.out.println(” :”+c卡塔尔国; 84 }else{ 85
System.out.println(“list为null”State of Qatar; 86 } 87 88 89 90
request.getSession(State of Qatar.setAttribute(“oid”,oid 卡塔尔国; 91
response.sendRedirect(“shopping-success.html”卡塔尔国; 92 93 94 } 95 96 97 98 }
99 100 } 生成订单的servlet

 

 

订单展现效果  &  查看历史订单

 

 

澳门新葡萄京娱乐场 6 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<ItemsOut> getPageList(int currentPage, int count卡塔尔(قطر‎ { 30 31 32
Connection con = null; 33 PreparedStatement ps = null; 34 ResultSet rs =
null; 35 List<ItemsOut> list = new ArrayList(State of Qatar; 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) * countState of Qatar;//
某页的起初数据 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(State of Qatar; 51 } finally { 52
JDBCUtils.release(rs, ps, con卡塔尔(قطر‎; 53 } 54 return null; 55 } 56 57 58
String username = “mxn”; 59 //
遵照姓名,获取到此姓名订单的具有数据,并分页呈现。 60 public
List<ItemsOut> getPageList1(int currentPage, int count卡塔尔 { 61 62
Connection con = null; 63 PreparedStatement ps = null; 64 ResultSet rs =
null; 65 List<Integer> list = new ArrayList(卡塔尔(قطر‎; 66
List<ItemsOut> 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(State of Qatar-1; j++State of Qatar { 82
in=in+list.get(j)+”,”; 83 } 84 in+=list.get(list.size(卡塔尔(قطر‎-1卡塔尔国; 85 //
System.out.println(“in—————“+inState of Qatar; 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(State of Qatar卡塔尔 { 93 l.add(toitem(rs卡塔尔国State of Qatar; 94
} 95 return l; 96 } catch (SQLException e卡塔尔国 { 97 // TODO Auto-generated
catch block 98 e.printStackTrace(State of Qatar; 99 }finally{ 100
JDBCUtils.release(rs, ps, con卡塔尔; 101 } 102 103 return null; 104 } 105 106
107 private ItemsOut toitem(ResultSet rsState of Qatar { 108 ItemsOut io = new
ItemsOut(卡塔尔国; 109 try { 110 io.setBookimg(rs.getString(“bookimg”卡塔尔卡塔尔; 111
io.setBookname(rs.getString(“bookname”State of QatarState of Qatar; 112
io.setDate(rs.getString(“date”卡塔尔卡塔尔; 113 io.setNumber(rs.getInt(“number”State of QatarState of Qatar;
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 block 122 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(1State of Qatar;// 重回第一条记录 138 } 139
} catch (Exception eState of Qatar { 140 e.printStackTrace(卡塔尔(قطر‎; 141 } finally { 142
JDBCUtils.release(rs, ps, con卡塔尔(قطر‎; 143 } 144 return 0; 145 } 146 147 public
int getTotalcount1(State of Qatar { 148 // TODO Auto-generated method stub 149 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<Integer> 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(State of Qatar; 174
if (rs.next(State of Qatar卡塔尔 { 175 reCount=rs.getInt(1卡塔尔(قطر‎; 176 } 177 } catch (Exception
e卡塔尔 { 178 e.printStackTrace(State of Qatar; 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 usernameState of Qatar { 190 this.username = username; 191 } 192
193 194 //向订单表中插入数据 195 public int
insertItem(List<ItemsIn> listState of Qatar{ 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 block 222
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[] argsState of Qatar { 237 //
List<Integer> list = new ArrayList(卡塔尔国; 238 ItemDAOImp id = new
ItemDAOImp(卡塔尔; 239 // id.setUsername(“ss”State of Qatar; 240 // List<ItemsOut>
list1 = id.getPageList1(1, 2卡塔尔(قطر‎; 241 // int s = id.getTotalcount1(State of Qatar; 242
//
System.out.println(“计算路数666666666666666666666666666666———-“+s卡塔尔;
243 // for (ItemsOut i : list1卡塔尔 { 244 //
System.out.println(i.getSumMoney(卡塔尔卡塔尔; 245 // } 246 // 247 //
System.exit(0State of Qatar; 248 // } 249 ItemsIn in = new ItemsIn(卡塔尔国; 250
in.setBook_id(1); 251 in.setNumber(2); 252 in.setO_id(2State of Qatar; 253
in.setSinglePrice(22State of Qatar; 254 in.setSumMoney(23State of Qatar; 255 List<ItemsIn>
list = new ArrayList(State of Qatar; 256 list.add(inState of Qatar; 257 id.insertItem(list卡塔尔(قطر‎; 258 }
259 } 订单展现和查经验史订单的dao层

 

 

 

澳门新葡萄京娱乐场 7 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 responseState of Qatar 28 throws ServletException, IOException {
29 String op = request.getParameter(“op”State of Qatar; 30 ItemDAOImp id = new
ItemDAOImp(State of Qatar; 31 //从session中得到oid 32
id.setOid((IntegerState of Qatarrequest.getSession(卡塔尔(قطر‎.getAttribute(“oid”卡塔尔(قطر‎卡塔尔国; 33 34 35
//从session中得到useranme 36
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
//从页面超链传来的 每页展现的数目count 46 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 //依照传来的参数 找到
当前页的数据集list 51 List<ItemsOut> list=
id.getPageList(Integer.parseInt(curpageIndexState of Qatar, Integer.parseInt(count卡塔尔国State of Qatar;
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”, listState of Qatar; 61 62
request.setAttribute(“pagecount”, pagenumState of Qatar; 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 =
(StringState of Qatarrequest.getSession(卡塔尔(قطر‎.getAttribute(“username”卡塔尔(قطر‎; 73
if(username==null卡塔尔国{ 74 response.sendRedirect(“login.jsp”State of Qatar; 75 }else{ 76
//从页面超链传来的 每页彰显的数量count 77 String count =
request.getParameter(“count”卡塔尔; 78 if(count == nullState of Qatar count =
“10”;//默许每页10条 79 String curpageIndex =
request.getParameter(“curpage”卡塔尔(قطر‎;//得到当前页的索引 80 if(curpageIndex ==
null卡塔尔(قطر‎ curpageIndex = “1”;//暗中同意是首页 81 //根据传来的参数 找到
当前页的多寡集list 82 List<ItemsOut> list1=
id.getPageList1(Integer.parseInt(curpageIndex卡塔尔国,
Integer.parseInt(count卡塔尔(قطر‎State of Qatar; 83 //获得总的数据量 84 int z1 =
id.getTotalcount1(卡塔尔国; 85 //依照传来的参数获得总页数 86 int pagenum1 =
(z1+Integer.parseInt(countState of Qatar-1State of Qatar/Integer.parseInt(count卡塔尔(قطر‎; 87
//将得到的当前页的数据集、总页数、和当前页重返给页面,页面实行展现 88
request.setAttribute(“list”, list1State of Qatar; 89
request.setAttribute(“pagecount”, pagenum1卡塔尔(قطر‎; 90
request.setAttribute(“currentPageIndex”,curpageIndexState of Qatar; 91
request.getRequestDispatcher(“orderhistory.jsp”State of Qatar.forward(request,
response卡塔尔国; 92 return ; 93 } 94 } 95 96 } 97 98 } 分页呈现订单和查看历史订单的servlet

 

 

 

澳门新葡萄京娱乐场 8 1 <%@
page language=”java” 2
import=”java.util.*,com.mm.bean.*,com.mm.Dao.impl.*” 3
pageEncoding=”UTF-8″%> 4 <%@ taglib prefix=”c”
uri=”; 5 <% 6 String path =
request.getContextPath(); 7 String basePath = request.getScheme() +
“://” 8 + request.getServerName() + “:” + request.getServerPort() 9 +
path + “/”; 10 11 List<ItemsOut> list =
(ArrayList<ItemsOut>) 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
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”> 26
<html> 27 <head> 28 <base href=”<%=basePath%>”>
29 <link type=”text/css” rel=”stylesheet” href=”css/style.css” />
30 <title>小编的订单</title> 31 32 </head> 33 34
<body> 35 <div id=”header” class=”wrap”> 36 <div
id=”logo”>武普鲁士蓝鸟英特网书城</div> 37 <div id=”navbar”> 38
<div class=”userMenu”> 39 <ul> 40 <li><a
href=”BookServlet?op=list”>应接您:${username }</a> 41
</li> 42 <li class=”current”><a
href=”orderlist.jsp”>笔者的订单</a> 43 </li> 44
<li><a href=”shopping.jsp”>购物车</a> 45 </li>
46 <li><a href=”#”>注销</a> 47 </li> 48
</ul> 49 </div> 50 <form method=”get” name=”search”
action=””> 51 寻找:<input class=”input-text” type=”text”
name=”keywords” /><input 52 class=”input-btn” type=”submit”
name=”submit” value=”” /> 53 </form> 54 </div> 55
</div> 56 <div id=”content” class=”wrap”> 57 <div
class=”list orderList”> 58 <table> 59 <tr class=”title”>
60 <th class=”orderId”>订单号码</th> 61
<th>订单商品</th> 62 <th
calss=”price”>订单名称</th> 63 <th
class=”userName”>收货人</th> 64 <th
class=”price”>订单单价</th> 65 <th
class=”price”>购买量</th> 66 <th
class=”price”>订单金额</th> 67 <th
class=”createTime”>下单时间</th> 68 <th
class=”status”>订单状态</th> 69 </tr> 70 71 <c:forEach
var=”item” items=”${list}”> 72 <tr> 73 <td>${item.o_id
}</td> 74 <td><img src=”${item.bookimg}” /></td>
75 <td>${item.bookname}</td> 76 <td>${item.username
}</td> 77 <td>${item.singlePrice}</td> 78
<td>${item.number }</td> 79 <td>${item.sumMoney
}</td> 80 <td>${item.date}</td> 81
<td>${item.state}</td> 82 </tr> 83 </c:forEach>
84 85 86 87 </table> 88 <div class=”page-spliter”> 89 90
<a href=”MyItemsServlet?op=list&count=5&curpage=1″>首页</a>
91 92 <c:choose> 93 <c:when test=”curpage = 1″> 94 <a
href=”#”>上一页</a> 95 </c:when> 96 <c:otherwise>
97 <%if(curpage>1){ %> 98 <a
href=”MyItemsServlet?op=list&count=2&curpage=<%=curpage –
1%>”>上一页</a> 99 100 <%} else{%> 101 <a
href=”MyItemsServlet?op=list&count=2&curpage=<%=curpage%>”>上一页</a>
102 103 <%} %> 104 </c:otherwise> 105 </c:choose> 106
107 <c:choose> 108 <c:when test=”curpage = pagenum”> 109
<a href=”#”>下风流浪漫页</a> 110 </c:when> 111
<c:otherwise> 112 113 <%if(curpage>=pagenum卡塔尔(قطر‎{ %> 114
<a
href=”MyItemsServlet?op=list&count=2&curpage=<%=curpage%>”>下意气风发页</a>
115 116 <%} else {%> 117 <a
href=”MyItemsServlet?op=list&count=2&curpage=<%=curpage+1%>”>下生龙活虎页</a>
118 119 <%} %> 120 </c:otherwise> 121 </c:choose> 122
<a
href=”MyItemsServlet?op=list&count=2&curpage=<%=pagenum%>”>尾页</a>
123 124 125 </div> 126 <div class=”button”> 127 128 <a
href = “MyItemsServlet?op=find”>查看历史订单</a> 129 130 131
</div> 132 </div> 133 </div> 134 <div id=”footer”
class=”wrap”>哈工大青鸟英特网书城 © 版权全数</div> 135 136 137
138 </body> 139 </html> 分页显示订单JSP

 

澳门新葡萄京娱乐场 9 1 <%@
page language=”java” 2
import=”java.util.*,com.mm.bean.*,com.mm.Dao.impl.*” 3
pageEncoding=”UTF-8″%> 4 <%@ taglib prefix=”c”
uri=”; 5 <% 6 String path =
request.getContextPath(); 7 String basePath = request.getScheme() +
“://” 8 + request.getServerName() + “:” + request.getServerPort() 9 +
path + “/”; 10 11 List<ItemsOut> list =
(ArrayList<ItemsOut>) 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
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”> 25
<html> 26 <head> 27 <base href=”<%=basePath%>”>
28 <link type=”text/css” rel=”stylesheet” href=”css/style.css” />
29 <title>作者的订单</title> 30 31 </head> 32 33
<body> 34 <div id=”header” class=”wrap”> 35 <div
id=”logo”>武棕色鸟英特网书城</div> 36 <div id=”navbar”> 37
<div class=”userMenu”> 38 <ul> 39 <li><a
href=”BookServlet?op=list”>迎接您:${username }</a> 40
</li> 41 <li class=”current”><a
href=”orderlist.jsp”>作者的订单</a> 42 </li> 43
<li><a href=”shopping.html”>购物车</a> 44 </li>
45 <li><a href=”#”>注销</a> 46 </li> 47
</ul> 48 </div> 49 <form method=”get” name=”search”
action=””> 50 搜索:<input class=”input-text” type=”text”
name=”keywords” /><input 51 class=”input-btn” type=”submit”
name=”submit” value=”” /> 52 </form> 53 </div> 54
</div> 55 <div id=”content” class=”wrap”> 56 <div
class=”list orderList”> 57 <table> 58 <tr class=”title”>
59 <th class=”orderId”>订单号码</th> 60
<th>订单商品</th> 61 <th
calss=”price”>订单名称</th> 62 <th
class=”userName”>收货人</th> 63 <th
class=”price”>订单单价</th> 64 <th
class=”price”>购买量</th> 65 <th
class=”price”>订单金额</th> 66 <th
class=”createTime”>下单时间</th> 67 <th
class=”status”>订单状态</th> 68 </tr> 69 70 <c:forEach
var=”item” items=”${list}”> 71 <tr> 72 <td>${item.o_id
}</td> 73 <td><img src=”${item.bookimg}” /></td>
74 <td>${item.bookname}</td> 75 <td>${item.username
}</td> 76 <td>${item.singlePrice}</td> 77
<td>${item.number }</td> 78 <td>${item.sumMoney
}</td> 79 <td>${item.date}</td> 80
<td>${item.state}</td> 81 </tr> 82 </c:forEach>
83 84 85 86 </table> 87 <div class=”page-spliter”> 88 89
<a href=”MyItemsServlet?op=find&count=5&curpage=1″>首页</a>
90 91 <c:choose> 92 <c:when test=”curpage = 1″> 93 <a
href=”#”>上一页</a> 94 </c:when> 95 <c:otherwise>
96 <%if(curpage>1){ %> 97 <a
href=”MyItemsServlet?op=find&count=5&curpage=<%=curpage –
1%>”>上一页</a> 98 99 <%} else{%> 100 <a
href=”MyItemsServlet?op=find&count=5&curpage=<%=curpage%>”>上一页</a>
101 102 <%} %> 103 </c:otherwise> 104 </c:choose> 105
106 <c:choose> 107 <c:when test=”curpage = pagenum”> 108
<a href=”#”>下风度翩翩页</a> 109 </c:when> 110
<c:otherwise> 111 112 <%if(curpage>=pagenumState of Qatar{ %> 113
<a
href=”MyItemsServlet?op=find&count=5&curpage=<%=curpage%>”>下风华正茂页</a>
114 115 <%} else {%> 116 <a
href=”MyItemsServlet?op=find&count=5&curpage=<%=curpage+1%>”>下生机勃勃页</a>
117 118 <%} %> 119 </c:otherwise> 120 </c:choose> 121
<a
href=”MyItemsServlet?op=find&count=5&curpage=<%=pagenum%>”>尾页</a>
122 123 124 </div> 125 <div class=”button”> 126 <input
class=”input-gray” type=”submit” name=”submit” 127
value=”查看三个月前的订单” /> 128 <input class=”input-gray”
type=”submit” 129 name=”submit” value=”查看贰个月前的订单” /> 130
<a href=”MyItemsServlet?op=find”>查看历史订单</a> 131 132
133 </div> 134 </div> 135 </div> 136 <div
id=”footer” class=”wrap”>浙紫浅豆沙色鸟网络书城 © 版权全数</div>
137 138 139 140 </body> 141 </html> 查看历史订单JSP

 

分页呈现图书音讯功用

 

澳门新葡萄京娱乐场 10 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<Book>
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<Book> 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(State of Qatar卡塔尔国{ 30 list.add(tobook(rsState of Qatar卡塔尔(قطر‎; 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 rsState of Qatar { 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”State of Qatar卡塔尔; 49
b.setBookprice(rs.getDouble(“bookprice”State of Qatar卡塔尔(قطر‎; 50
b.setBookauthor(rs.getString(“bookauthor”卡塔尔(قطر‎卡塔尔; 51
b.setBookcontent(rs.getString(“bookcontent”卡塔尔State of Qatar; 52
b.setBookimg(rs.getString(“bookimg”卡塔尔(قطر‎State of Qatar; 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(State of Qatar; 72 if(rs.next(State of Qatar卡塔尔{ 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<Book> 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(State of Qatar; 91 List<Book> 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 eState of Qatar { 106 // TODO Auto-generated catch block 107
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 stub 116
Connection con = null; 117 PreparedStatement ps = null; 118 ResultSet rs
= null; 119 Book book = new Book(State of Qatar; 120 try { 121 con =
JDBCUtils.getconnection(卡塔尔; 122 String sql = “select * from book where
bookid =?”; 123 ps = con.prepareStatement(sql卡塔尔; 124 ps.setInt(1, bidState of Qatar;
125 rs = ps.executeQuery(State of Qatar; 126 while(rs.next(State of Qatar卡塔尔国{ 127 return tobook(rs卡塔尔(قطر‎;
128 } 129 130 } catch (SQLException e卡塔尔 { 131 // TODO Auto-generated
catch block 132 e.printStackTrace(卡塔尔(قطر‎; 133 }finally{ 134
JDBCUtils.release(rs, ps, con卡塔尔国; 135 } 136 return null; 137 } 138 139
}show 分页展现图书servlet层的管理

 

澳门新葡萄京娱乐场 11 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(State of Qatar; 1918 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卡塔尔State of Qatar{ 35
//从页面超链传来的 每页展现的数目count 36 String count =
request.getParameter(“count”卡塔尔; 37 if(count == null卡塔尔 count =
“10”;//默许每页10条 38 String curpageIndex =
request.getParameter(“curpage”State of Qatar;//获得当前页的索引 39 if(curpageIndex ==
null卡塔尔国 curpageIndex = “1”;//暗许是首页 40 //根据传来的参数 找到
当前页的数量集list 41 List<Book> list=
bs.getPageList(Integer.parseInt(curpageIndex卡塔尔国, Integer.parseInt(count卡塔尔(قطر‎卡塔尔;
42 43 //依照传来的参数获得总页数 44 int pagenum =
bs.Pagecount(Integer.parseInt(count卡塔尔国卡塔尔(قطر‎; 45
//将得到的当前页的数据集、总页数、和当前页再次回到给页面,页面举办展示 46
request.setAttribute(“list”, listState of Qatar; 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 == nullState of Qatar count =
“10”;//暗中同意每页10条 59 List<Book> book =
bs.findbookByName(booknameState of Qatar;//依据书名找到书的集合 60
request.setAttribute(“list”, book卡塔尔(قطر‎; 61
request.getRequestDispatcher(“showbook.jsp”State of Qatar.forward(request, responseState of Qatar;
62 return ; 63 } 64 65 } 66 67 68 } 图书显示JSP

 

实习就要截至了,最终要上交的是网络书城项目和生机勃勃份文档。接下来简单介绍一下体系。
项目是基于三…

    public  DBHelper(){
        try {
            Class.forName(“oracle.jdbc.driver.OracleDriver”State of Qatar; 
//装载驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

复制代码 代码如下:

3.创制 Servlet 对显示页面进行支配

<%@ page language=”java”
import=”java.util.*,page.bean.Contact,page.bean.PageResultSet”
pageEncoding=”gb2312″%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + “://”

import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.Date;

复制代码 代码如下:

web.xml 中的配置文件为:

1.之下是得以达成分页的类PageResultSet

    /**
     * 获取当前页的数码
     * @param curPage
     * @param rowsPerPage
     * @return
     */
    public List<UserData> getData(int curPage, int rowsPerPage) {

有热心网上基友回复:
str += ” 转到<select name=’page’ onChange=”window.location.href='”

package com.dao;

package page.bean;
import java.util.*;
public class PageResultSet {
/**
* 分页数据
*/
private Collection data = null;
/**
* 当前页
*/
private int curPage;
/**
* 每页展现的记录数
*/
private int pageSize;
/**
* 记录行数
*/
private int rowsCount;
/**
* 页数
*/
private int pageCount;
public PageResultSet(Collection data) {
this.data = data;
this.curPage = 1;
this.pageSize = 10;
this.rowsCount = data.size();
this.pageCount = (int) Math.ceil((double) rowsCount / pageSize);
}
public PageResultSet(Collection data, int curPage) {
this.data = data;
this.curPage = curPage;
this.pageSize = 10;
this.rowsCount = data.size();
this.pageCount = (int) Math.ceil((double) rowsCount / pageSize);
}
public PageResultSet(Collection data, int curPage, int pageSize) {
this.data = data;
this.curPage = curPage;
this.pageSize = pageSize;
this.rowsCount = data.size();
this.pageCount = (int) Math.ceil((double) rowsCount / pageSize);
}
/**
* getCurPage:重临当前的页数
*
* @return int
*/
public int getCurPage() {
return curPage;
}
/**
* getPageSize:重临分页大小
*
* @return int
*/
public int getPageSize() {
return pageSize;
}
/**
* getRowsCount:再次回到总记录行数
*
* @return int
*/
public int getRowsCount() {
return rowsCount;
}
/**
* getPageCount:再次来到总页数
*
* @return int
*/
public int getPageCount() {
return pageCount;
}
/**
* 第一页
*
* @return int
*/
public int first() {
return 1;
}
/**
* 最平生龙活虎页
*
* @return int
*/
public int last() {
return pageCount;
}
/**
* 上一页
*
* @return int
*/
public int previous() {
return (curPage – 1 < 1) ? 1 : curPage – 1;
}
/**
* 下一页
*
* @return int
*/
public int next() {
return (curPage + 1 > pageCount) ? pageCount : curPage + 1;
}
/**
* 第一页
*
* @return boolean
*/
public boolean isFirst() {
return (curPage == 1) ? true : false;
}
/**
* 最终生机勃勃页
*
* @return boolean
*/
public boolean isLast() {
return (curPage == pageCount) ? true : false;
}
/** * 获取当前页数据
*
* @return Collection
*/
public Collection getData() {
Collection curData = null;
if (data != null) {
int start = (curPage – 1) * pageSize;
int end = 0;
if (start + pageSize > rowsCount)
end = rowsCount;
else
end = start + pageSize;
ArrayList arrayCurData = new ArrayList();
ArrayList arrayData = null;
Vector vectorCurData = new Vector();
Vector vectorData = null;
boolean isArray = true;
if (data instanceof ArrayList) {
arrayData = (ArrayList) data;
isArray = true;
} else if (data instanceof Vector) {
vectorData = (Vector) data;
isArray = false;
}
for (int i = start; i < end; i++) {
if (isArray) {
arrayCurData.add(arrayData.get(i));
} else {
vectorData.add(vectorData.elementAt(i));
}
}
if (isArray) {
curData = (Collection) arrayCurData;
} else {
curData = (Collection) vectorCurData;
}
}
return curData;
}
/**
* 获取工具条
*
* @return String
*/
public String getToolBar(String fileName) {
String temp = “”;
if (fileName.indexOf(“?”) == -1) {
temp = “?”;
} else {
temp = “&”;
}
String str = “<form method=’post’ name=’frmPage’ action='” + fileName

package com.servlet;

您恐怕感兴趣的篇章:

  • jsp分页展现的贯彻代码
  • JSP分页展现的实例代码
  • jsp hibernate的分页代码
  • JSP完成的简易分页示例
  • JSP自定义分页标签TAG全经过
  • 八个通用的jsp分页PageBean
  • jsp读取数据库完成分页本领简析
  • jsp+servlet+javabean达成数量分页方法完整实例
  • jsp分页展现完整实例
  • 轻松易行完结JSP分页呈现效果

/**
 * Created by lx_sunwei on 14-1-6.
 */
public class UserData {

  • request.getServerName() + “:” + request.getServerPort()
  • path + “/”;
    %>
    <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
    <html>
    <head>
    <base href=”<%=basePath%>”>
    <title>My JSP ‘index.jsp’ starting page</title>
    <meta http-equiv=”pragma” content=”no-cache”>
    <meta http-equiv=”cache-control” content=”no-cache”>
    <meta http-equiv=”expires” content=”0″>
    <meta http-equiv=”keywords”
    content=”keyword1,keyword2,keyword3″>
    <meta http-equiv=”description” content=”This is my page”>
    <!–
    <link rel=”stylesheet” type=”text/css” href=”styles.css”>
    –>
    </head>
    <body>
    <table border=”1″>
    <%
    PageResultSet pageResultSet = (PageResultSet)
    request.getAttribute(“usersList”);
    ArrayList usersList = (ArrayList) pageResultSet.getData();
    for (int i = 0; i < usersList.size(); i++) {
    Contact co = (Contact) usersList.get(i);
    %>
    <tr>
    <td>
    <%=co.getId() %>
    </td>
    <td>
    <a
    href=”login.do?id=<%=co.getId()%>”><%=co.getUsername()%></a>
    </td>
    <td>
    <%=co.getMobile() %>
    </td>
    <td>
    <%=co.getMail() %>
    </td>
    <td>
    <%=co.getPhone() %>
    </td>
    <td>
    <%=co.getMem() %>
    </td>
    <td>
    <%=co.getLastcontact() %>
    </td>
    </tr>
    <%
    }
    %>
    </table>
    <!– 呈现分页工具栏 –>
    <%=pageResultSet.getToolBar(“login.do”)%>
    </body>
    </html>

    public BigDecimal getComm() {
        return comm;
    }

2.一下是Action

    protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
        doPost(request,response);
    }
}

  • fileName + temp +
    “cur_page=’+this.options[this.selectedIndex].value”>”;
    现已试过了,没难题

/**
 * Created by lx_sunwei on 14-1-6.
 */
public class Servlet extends HttpServlet {

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package struts.action;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import page.bean.DatabaseConn;
import page.bean.PageResultSet;
import page.bean.ContactBO;
import struts.form.LoginForm;
/**
* MyEclipse Struts
* Creation date: 04-02-2008
*
* XDoclet definition:
* @struts.action path=”/login” name=”loginForm” input=”/login.jsp”
scope=”request” validate=”true”
* @struts.action-forward name=”sss” path=”/index.jsp”
*/
public class LoginAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm loginForm = (LoginForm) form;
ContactBO userBO=new ContactBO();
//先从事情管理逻辑类中抽取数据(ArrayList或Vector格式卡塔尔国
Collection data;
try {
data = userBO.findContact(DatabaseConn.getConnection());
//再赢妥当前页curPage和每页记录数pageSize
//int curPage =
Integer.parseInt((String)request.getParameter(“cur_page”));
int curPage = 1;
String cur = request.getParameter(“cur_page”);
System.out.println(“————–: “+cur);
if(cur!=null && cur !=””){
curPage = new Integer(cur).intValue();
}
int pageSize=10;
//然后生成PageResultSet对象
PageResultSet dataList = new PageResultSet(data, curPage, pageSize);
request.setAttribute(“usersList”, dataList);
return mapping.findForward(“sss”);
} catch (Exception e) {
e.printStackTrace();
return mapping.getInputForward();
}
}
}

把品种构造到 Tomcat 服务器上,输入地点:  
那样就能够见见到效果果

3.以下是展示分页的页面

    public void setDeptno(BigDecimal deptno) {
        this.deptno = deptno;
    }

  • “‘>”;
    str += “<p align=’center’>”;
    if (isFirst())
    str += “首页 上一页 “;
    else {
    str += “<a href='” + fileName + temp +
    “cur_page=1′>首页</a> “;
    str += “<a href='” + fileName + temp + “cur_page=” + (curPage – 1) +
    “‘>上一页</a> “;
    }
    if (isLast())
    str += “下一页 尾页 “;
    else {
    str += “<a href='” + fileName + temp + “cur_page=” + (curPage + 1) +
    “‘>下一页</a> “;
    str += “<a href='” + fileName + temp + “cur_page=” + pageCount +
    “‘>尾页</a> “;
    }
    str += ” 共<b>” + rowsCount + “</b>条记录 “;
    str += ” 转到<select name=’page’ onChange=”location='” + fileName
  • temp + “cur_page=’+this.options[this.selectedIndex].value”>”;
    for (int i = 1; i <= pageCount; i++) {
    if (i == curPage)
    str += “<option value='” + i + “‘ selected>第” + i +
    “页</option>”;
    else
    str += “<option value='” + i + “‘>第” + i + “页</option>”;
    }
    str += “</select></p></form>”;
    return str;
    }
    }

    public String getJob() {
        return job;
    }

</web-app>

    public Date getHireDate() {
        return hireDate;
    }

1.先是创立二个对象 UserData,用以保存从数据库中收获的多寡。

    protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
        String curPage1 = request.getParameter(“page”卡塔尔; 
//获取当前页页码
        if (curPage1 == null){
            curPage = 1;
            request.setAttribute(“curPage”,curPage); 
//设置curPage对象
        }else {
            curPage = Integer.parseInt(curPage1);
            if (curPage < 1){
                curPage = 1;
            }
            request.setAttribute(“curPage”,curPage);
        }

    public int rowsPerPage;  //每页呈现的行数
    public int curPage;  //当前页页码
    public int maxPage;  //总共页数
    DBHelper db = new DBHelper();
    public Servlet(){
        rowsPerPage = 5;
    }

        List<UserData> dataList = new ArrayList<>();
        String url = “jdbc:oracle:thin:@localhost:1521:orcl”;
        try {
            conn = DriverManager.getConnection(url,”scott”,”tiger”);
            String sql = “select * from emp where rownum <= ((? – 1)
* “+rowsPerPage+” + “+rowsPerPage+”) minus ” +
                    ” select * from emp where rownum <= (? – 1) *
“+rowsPerPage+” “;
            pt = conn.prepareStatement(sql);
            pt.setInt(1,curPage);
            pt.setInt(2,curPage);
            rs = pt.executeQuery();
            while (rs.next()){
                /**
                 * 从结果集中拿到数据
                 */
                UserData userData = new UserData();
                BigDecimal empno = rs.getBigDecimal(“empno”);
                String ename = rs.getString(“ename”);
                String job = rs.getString(“job”);
                BigDecimal mgr = rs.getBigDecimal(“mgr”);
                Date hireDate = rs.getDate(“hiredate”);
                BigDecimal sal = rs.getBigDecimal(“sal”);
                BigDecimal comm = rs.getBigDecimal(“comm”);
                BigDecimal deptno = rs.getBigDecimal(“deptno”);
                /**
                 * 设置对象属性
                 */
                userData.setEmpno(empno);
                userData.setEname(ename);
                userData.setJob(job);
                userData.setMgr(mgr);
                userData.setHireDate(hireDate);
                userData.setSal(sal);
                userData.setComm(comm);
                userData.setDeptno(deptno);
                dataList.add(userData卡塔尔(قطر‎;  //把对象增添集合中
            }
            rs.close();
            pt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataList;
    }

import com.tool.UserData;

    public String getEname() {
        return ename;
    }

    public void setJob(String job) {
        this.job = job;
    }
}

4.创设 JSP 页面,显示数据。

import java.math.BigDecimal;
import java.util.Date;

package com.tool;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import com.dao.DBHelper;
import com.tool.UserData;

    public BigDecimal getMgr() {
        return mgr;
    }

    public BigDecimal getSal() {
        return sal;
    }

<%@ page import=”java.util.List” %>
<%@ page import=”com.tool.UserData” %>
<%@ page contentType=”text/html;charset=UTF-8″ language=”java”
%>
<html>
<head>
    <title>servlet数据分页</title>
    <link rel=”stylesheet” type=”text/css” href=”css.css”>
</head>
<body>
<div style=”margin-top: 15%; margin-left: 25%”>
    <table>
        <caption>SCOTT客商,EMP表中的数据</caption>
        <%! int curPage,maxPage; %>
        <% curPage
=Integer.parseInt(request.getAttribute(“curPage”).toString()); %>
<!–取妥帖前页–>
        <% maxPage
=Integer.parseInt((String)request.getAttribute(“maxPage”).toString());
%> <!–获得总页数–>
        <%if (request.getAttribute(“dataList”) == null){
        %>
        <tr>
            <td colspan=”8″>未有数量</td>
        </tr>
        <%
        }else {
        %>
        <tr>
            <!–表头–>
            <th>EMPNO</th>
            <th>ENAME</th>
            <th>JOB</th>
            <th>MGR</th>
            <th>HIREDATE</th>
            <th>SAL</th>
            <th>COMM</th>
            <th>DEPTNO</th>
        </tr>
        <%
            List list = (List) request.getAttribute(“dataList”);
            for (Object aList : list) {
                UserData userData = (UserData) aList;
        %>
        <tr>
            <!–得到表中数据–>
            <td><%= userData.getEmpno() %></td>
            <td><%= userData.getEname() %></td>
            <td><%= userData.getJob() %></td>
            <td><%= userData.getMgr() %></td>
            <td><%= userData.getHireDate() %></td>
            <td><%= userData.getSal() %></td>
            <td><%= userData.getComm() %></td>
            <td><%= userData.getDeptno() %></td>
        </tr>
        <%
                }
            }
        %>
    </table>
</div>
<div style=”margin-top: 8%; margin-left: 29%”>
    第<%= curPage %>页,共<%= maxPage %>页  
    <%if (curPage > 1){
    %>
    <a href=”Servlet?page=1″>首页</a>
    <a href=”Servlet?page=<%=curPage –
1%>”>上一页</a>
    <%
    }else {
    %>
    首页 上一页
    <%
        }%>
    <%if (curPage < maxPage){
    %>  
    <a href=”Servlet?page=<%=curPage +
1%>”>下一页</a>
    <a href=”Servlet?page=<%=maxPage%20%>”>尾页</a>
    <%
    }else {
    %>
    下一页 尾页
    <%
        }%>
      转至第 <form name=”form1″ action=”Servlet” method=”get”>
    <label>
        <select name=”page” onchange=”document.form1.submit()”>
            <%for ( int i = 1; i <= maxPage; i++){
                if (i == curPage){
            %>
            <!–当前页页码私下认可选中–>
            <option selected value=”<%= i%>”><%= i
%></option>
            <%
            }else {
            %>
            <option value=”<%= i %>”><%= i
%></option>
            <%
                    }
                }%>
        </select>
    </label>
</form> 页
</div>
</body>
</html>

    public void setComm(BigDecimal comm) {
        this.comm = comm;
    }

    /**
     * 再次回到总页数
     * @return
     */
    public int getMaxPage(int rowsPerPage) {
        int maxPage;
        int maxRowCount = 0;
        String url = “jdbc:oracle:thin:@localhost:1521:orcl”;
        try {
            conn = DriverManager.getConnection(url,”scott”,”tiger”State of Qatar; 
//创立数据库连接
            String sql = “select count(*) from emp”;
            pt = conn.prepareStatement(sql);
            rs = pt.executeQuery();
            if (rs.next()){
                maxRowCount = rs.getInt(1);  //总行数
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        maxPage = (maxRowCount + rowsPerPage – 1) / rowsPerPage; 
//总页数
        return maxPage;
    }
}

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>com.servlet.Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/Servlet</url-pattern>
    </servlet-mapping>

    public void setMgr(BigDecimal mgr) {
        this.mgr = mgr;
    }

    public BigDecimal getEmpno() {
        return empno;
    }

2.创立三个 DBHelper 对象用以与数据库实行相互影响

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns=””
           xmlns:xsi=””
           xsi:schemaLocation=”
          “
           version=”3.0″>

    Connection conn;  //数据库连接对象
    PreparedStatement pt;  //SQL语句预管理对象
    ResultSet rs;  //结果集对象

    public void setSal(BigDecimal sal) {
        this.sal = sal;
    }

/**
 * Created by lx_sunwei on 14-1-6.
 */
public class DBHelper {

    public void setEmpno(BigDecimal empno) {
        this.empno = empno;
    }

        RequestDispatcher rd =
request.getRequestDispatcher(“pagemain.jsp”卡塔尔; 
//将诉求转载到pagemain.jsp页面
        rd.forward(request,response);
    }

        List<UserData> dataList;
        dataList = db.getData(curPage,rowsPerPage卡塔尔; 
//获取当前页的数量
        maxPage = db.getMaxPage(rowsPerPageState of Qatar;  //获取总页数
        request.setAttribute(“dataList”,dataList);
        request.setAttribute(“maxPage”, maxPage);

    /**
     * EMP表中的数据属性
     */
    private String ename;
    private String job;
    private BigDecimal empno;
    private BigDecimal mgr;
    private Date hireDate;
    private BigDecimal sal;
    private BigDecimal comm;
    private BigDecimal deptno;

发表评论

电子邮件地址不会被公开。 必填项已用*标注