Java如何实现后端分页

工具:myeclipse ,数据库:Oracle ,jar包:classes12.jar

实现的功能:对客户的增删改查,展示客户列表,一页显示十条客户数据,实现分条件查询(根据ID,名称等)

这个小Demo用到了:

1,使用jsp+servlet,工厂模式,代理类

2,后端分页技术

3,ajax前后台交互

代码如下:

/**
 *客户接口类
 */
public interface CustomerDAO {
	/**
	 * @param pojo 客户类
	 * @return 新增客户
	 */
	public boolean doIns(CustomerPOJO pojo);
	/**
	 * @param customerId  客户id
	 * @return 删除客户
	 */
	public boolean doDel(BigDecimal customerId);
	/**
	 * @param pojo  客户类
	 * @return 更新客户信息
	 */
	public boolean doUpd(CustomerPOJO pojo);
	/**
	 * @param customerId
	 * @return 根据客户id,名称查询客户所有信息
	 */
	public CustomerPOJO findById(BigDecimal cid);
	/**
	 * @param customerName
	 * @return 根据客户名查询全部信息
	 */
	public CustomerPOJO findByName(String cname);
	/**
	 * 列出所有客户
	 */
	public List<CustomerPOJO> findAll(int pageSize, int pageCurrent);

	/**
	 *查询客户数量
	 */
	public int findAllCount();
}

接口实现类:

public class CustomerDAOImpl implements CustomerDAO {
   Connection conn;
   public CustomerDAOImpl(Connection conn){
      this.conn = conn;
   }
   public boolean doIns(CustomerPOJO pojo) {
      boolean flag=false;
      PreparedStatement pstate = null;
      try {
         this.conn.setAutoCommit(false);
         String sql="insert into customer(customer_id,customer_name,customer_sex,customer_tel,customer_adress,customer_pro_id)values(DH1.nextval,?,?,?,?,?)";
         pstate = this.conn.prepareStatement(sql);
         pstate.setString(1,pojo.getCustomerName());
         pstate.setInt(2,pojo.getCustomerSex());
         pstate.setString(3,pojo.getCustomerTel());
         pstate.setString(4,pojo.getCustomerAdress());
         pstate.setBigDecimal(5,pojo.getCustomerProId());
         pstate.execute();
         this.conn.commit();
         flag = true;
      } catch (SQLException e) {
         e.printStackTrace();
         try {
            this.conn.rollback();
         } catch (SQLException e1) {
            e1.printStackTrace();
         }
      }finally{
         try {
            pstate.close();
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
      return flag;
   }

   public boolean doDel(BigDecimal customerId) {//伪删除,使信息不可见,方便误删找回
      boolean flag = false;
      PreparedStatement pstate = null;
      try {
         this.conn.setAutoCommit(false);
         String sql = "update customer set is_delete=0 wherecustomer_id = ?";
         pstate = this.conn.prepareStatement(sql);
         pstate.setBigDecimal(1, customerId);
         pstate.execute();
         this.conn.commit();
         flag = true;
      } catch (SQLException e) {
         e.printStackTrace();
         try {
            this.conn.rollback();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      } finally{
         try {
            pstate.close();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return flag;
   }

   public boolean doUpd(CustomerPOJO pojo) {
      boolean flag = false;
      PreparedStatement pstate = null;
      try {
         this.conn.setAutoCommit(false);
         String sql = "update customer setcustomer_name=?,password=?,customer_sex=?,customer_tel=?,customer_adress=?,customer_pro_id=?,is_delete=?,role_mark=?where customer_id=?";
         pstate = this.conn.prepareStatement(sql);
         pstate.setBigDecimal(1,pojo.getCustomerId());
         pstate.setString(2,pojo.getCustomerName());
         pstate.setString(3,pojo.getPassword());
         pstate.setInt(4,pojo.getCustomerSex());
         pstate.setString(5,pojo.getCustomerTel());
         pstate.setString(6, pojo.getCustomerAdress());
         pstate.setBigDecimal(7,pojo.getCustomerProId());
         pstate.setInt(8, pojo.getIsDelete());
         pstate.setInt(9, pojo.getRoleMark());
         pstate.execute();
         this.conn.commit();
         flag = true;
      } catch (Exception e) {
         e.printStackTrace();
         try {
            this.conn.rollback();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      } finally{
         try {
            pstate.close();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return flag;
   }

   public CustomerPOJO findById(BigDecimal customerId) {
      CustomerPOJO pojo = null;
      PreparedStatement pstate = null;
      ResultSet res = null;
      String sql = "select customer_name, password,customer_sex, customer_tel, customer_adress, customer_pro_id, is_delete, role_markfrom customer where customer_id = ? and is_delete=1";
      try {
         pstate = this.conn.prepareStatement(sql);
         pstate.setBigDecimal(1, customerId);
         res = pstate.executeQuery();
         while(res.next()){
            pojo=new CustomerPOJO(customerId,res.getString(1),res.getString(2),res.getInt(3),res.getString(4),res.getString(5),res.getBigDecimal(6),res.getInt(7),res.getInt(8));

         }
      } catch (SQLException e) {
         e.printStackTrace();
      }finally{
         try {
            res.close();
            pstate.close();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return pojo;
   }

   public CustomerPOJO findByName(String customerName) {
      CustomerPOJO pojo = null;
      PreparedStatement pstate = null;
      ResultSet res = null;
      String sql = "select customer_id, password,customer_sex, customer_tel, customer_adress, customer_pro_id, is_delete,role_mark from customer where customer_name = ? and is_delete=1";
      try {
         pstate = this.conn.prepareStatement(sql);
         pstate.setString(1, customerName);
         res = pstate.executeQuery();
         while(res.next()){
            pojo=newCustomerPOJO(res.getBigDecimal(1),customerName,res.getString(2),res.getInt(3),res.getString(4),res.getString(5),res.getBigDecimal(6),res.getInt(7),res.getInt(8));

         }
      } catch (SQLException e) {
         e.printStackTrace();
      }finally{
         try {
            res.close();
            pstate.close();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return pojo;
   }
   public List<CustomerPOJO> findAll(int pageSize, int pageCurrent) {
      List<CustomerPOJO> list = new ArrayList<CustomerPOJO>();
      PreparedStatement pstate = null;
      ResultSet res = null;
      String sql = "select customer_id, customer_name,password, customer_sex, customer_tel, customer_adress, customer_pro_id,is_delete, role_mark  from " +
           "(select customer_id, customer_name,password, customer_sex, customer_tel, customer_adress, customer_pro_id,is_delete, role_mark, rownum as rn from customer)  where rn > ? andrn<=? and is_delete = 1" ;
      try {
         pstate = this.conn.prepareStatement(sql);
         pstate.setInt(1,(pageCurrent-1)*pageSize);
         pstate.setInt(2, pageCurrent*pageSize);
         res = pstate.executeQuery();
         while(res.next()){
            CustomerPOJO pojo=newCustomerPOJO(res.getBigDecimal(1),res.getString(2),res.getString(3),res.getInt(4),res.getString(5),res.getString(6),res.getBigDecimal(7),res.getInt(8),res.getInt(9));
            list.add(pojo);
         }
      } catch (SQLException e) {
         e.printStackTrace();
      }finally{
         try {
            res.close();
            pstate.close();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return list;
   }
   public int findAllCount() {
      int count = 0;
      PreparedStatement pstate = null;
      ResultSet res = null;
      String sql = "select count(customer_id) fromcustomer" ;
      try {
         pstate = this.conn.prepareStatement(sql);
         res = pstate.executeQuery();
         while(res.next()){
            count = res.getInt(1);
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally{
         try {
            res.close();
            pstate.close();
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return count;
   }
}

代理类:

public class CustomerDAOProxy implements CustomerDAO {
	Connection conn = null;
	CustomerDAOImpl impl=null;
	public CustomerDAOProxy(){
		try {
			this.conn=JDBCHelper.getConn();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.impl=new CustomerDAOImpl(this.conn);
	}
	public boolean doIns(CustomerPOJO pojo) {
		boolean flag = this.impl.doIns(pojo);
		this.close();
		return flag;
	}
	public boolean doDel(BigDecimal customerId) {
		boolean flag = this.impl.doDel(customerId);
		this.close();
		return flag;
	}
	public boolean doUpd(CustomerPOJO pojo) {
		boolean flag = this.impl.doUpd(pojo);
		this.close();
		return flag;
	}
	public CustomerPOJO findById(BigDecimal cid) {
		CustomerPOJO pojo = this.impl.findById(cid);
		this.close();
		return pojo;

	}
	public CustomerPOJO findByName(String cname) {
		CustomerPOJO pojo = this.impl.findByName(cname);
		this.close();
		return pojo;
	}
	public List<CustomerPOJO> findAll(int pageSize, int pageCurrent) {
		List<CustomerPOJO> list=this.impl.findAll(pageSize, pageCurrent);
		this.close();
		return list;
	}
	public int findAllCount() {
		int count=this.impl.findAllCount();
		this.close();
		return count;
	}
	public void close(){
		try {
			this.conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

工厂类:

public class CustomerDAOFactory {
	public static CustomerDAO getDAOInstance(){
		return new CustomerDAOProxy();
	}
}

public class AddCustomer extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String cname = request.getParameter("cname");
		int csex = Integer.parseInt(request.getParameter("csex"));
		String ctel = request.getParameter("ctel");
		String cadress = request.getParameter("cadress");
		BigDecimal cpid = new BigDecimal(request.getParameter("cpid"));
		CustomerPOJO pojo = new CustomerPOJO(cname,csex,ctel,cadress,cpid);
		System.out.println("输出数据:"+pojo.toString());
		boolean flag=CustomerDAOFactory.getDAOInstance().doIns(pojo);
		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append(flag);
		out.print(sb.toString());
		out.close();
	}

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

}

Servlet处理类

 CustomerQuery 客户数据查询:

public class CustomerQuery extends HttpServlet {
	private static final long serialVersionUID = 1225972715083060475L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		if(request.getParameter("customerId")!=null){//如果ID有输入,显示该ID的客户
		BigDecimal customerId = new BigDecimal(request.getParameter("customerId"));
		CustomerPOJO pojo = CustomerDAOFactory.getDAOInstance().findById(customerId);
		request.setAttribute("pojo", pojo);
		String str="";
		if(pojo.getCustomerSex()==1){
			str="男";
		}else{
			str="女";
		}
		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append("<table id='mytable'><tr><th>客户ID</th><th>客户名称</th><th>客户密码</th><th>客户性别</th><th>联系方式</th><th>客户住址</th><th>购买产品id</th><th>操作</th></tr>");
		sb.append("<tr>" +
				"<td>"+pojo.getCustomerId()+"</td>" +
				"<td>"+pojo.getCustomerName()+"</td>" +
				"<td>"+pojo.getPassword()+"</td>" +
				"<td>"+str+"</td>" +
				"<td>"+pojo.getCustomerTel()+"</td>" +
				"<td>"+pojo.getCustomerAdress()+"</td>" +
				"<td>"+pojo.getCustomerProId()+"</td>" +
				"<td><a href='#' onclick='goUpdate("+pojo.getCustomerId()+")'>修改</a>    <a href='#' onclick='goDelete("+pojo.getCustomerId()+")'>删除</a></td>" +
				"</tr>");
				sb.append("</table>");
				out.print(sb.toString());
				out.close();
		}
		else if(request.getParameter("customerName")!=null){//如果名字有输入,显示该姓名的客户
			String customerName = request.getParameter("customerName");
			CustomerPOJO pojo = CustomerDAOFactory.getDAOInstance().findByName(customerName);
			request.setAttribute("pojo", pojo);
			String str="";
			if(pojo.getCustomerSex()==1){
				str="男";
			}else{
				str="女";
			}
			PrintWriter out = response.getWriter();
			StringBuffer sb = new StringBuffer();
			sb.append("<table id='mytable'><tr><th>客户ID</th><th>客户名称</th><th>客户密码</th><th>客户性别</th><th>联系方式</th><th>客户住址</th><th>购买产品id</th><th>操作</th></tr>");
			sb.append("<tr>" +
					"<td>"+pojo.getCustomerId()+"</td>" +
					"<td>"+pojo.getCustomerName()+"</td>" +
					"<td>"+pojo.getPassword()+"</td>" +
					"<td>"+str+"</td>" +
					"<td>"+pojo.getCustomerTel()+"</td>" +
					"<td>"+pojo.getCustomerAdress()+"</td>" +
					"<td>"+pojo.getCustomerProId()+"</td>" +
					"<td><a href='#' onclick='goUpdate("+pojo.getCustomerId()+")'>修改</a>    <a href='#' onclick='goDelete("+pojo.getCustomerId()+")'>删除</a></td>" +
					"</tr>");
					sb.append("</table>");
					out.print(sb.toString());
					out.close();
		}else{//ID 和名字都没有输入,显示全部客户列表
			int pageSize = Integer.parseInt(request.getParameter("pageSize"));//得到一页显示的数据笔数
			int pageCurrent = Integer.parseInt(request.getParameter("pageCurrent"));//得到要显示哪一页的数据
			List<CustomerPOJO> list = CustomerDAOFactory.getDAOInstance().findAll(pageSize, pageCurrent);
			int count=CustomerDAOFactory.getDAOInstance().findAllCount();
			PrintWriter out = response.getWriter();
			StringBuffer sb = new StringBuffer();
			sb.append("<input type='hidden' id='count' value='"+count+"'/>");
			sb.append("<table id='mytable'><tr><th>客户ID</th><th>客户名称</th><th>客户密码</th><th>客户性别</th><th>联系方式</th><th>客户住址</th><th>购买产品id</th><th>操作</th></tr>");
			for(CustomerPOJO pojo : list){
				String str="";
				if(pojo.getCustomerSex()==1){
					str="男";
				}else{
					str="女";
				}
				sb.append("<tr>" +
						"<td>"+pojo.getCustomerId()+"</td>" +
						"<td>"+pojo.getCustomerName()+"</td>" +
						"<td>"+pojo.getPassword()+"</td>" +
						"<td>"+str+"</td>" +
						"<td>"+pojo.getCustomerTel()+"</td>" +
						"<td>"+pojo.getCustomerAdress()+"</td>" +
						"<td>"+pojo.getCustomerProId()+"</td>" +
						"<td><a href='#' onclick='goUpdate("+pojo.getCustomerId()+")'>修改</a>    <a href='#' onclick='goDelete("+pojo.getCustomerId()+")'>删除</a></td>" +
						"</tr>");
			}
			sb.append("</table>");
			sb.append("<input type='button' id='first' value='|<' onclick='query(1)'/>");
			sb.append("<input type='button' id='up' value='<' onclick='query(2)'/>");
			sb.append("<input type='button' id='next' value='>' onclick='query(3)'/>");
			sb.append("<input type='button' id='end' value='>|' onclick='query(4)'/>");
			sb.append("<span id='showPageMessage'></span>");
			out.print(sb.toString());
			out.close();
		}
	}

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

CustomerUpd   客户数据更新:

public class CustomerUpd extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		BigDecimal customerId = new BigDecimal(request.getParameter("cid"));
		String customerName = request.getParameter("cname");
		String password = request.getParameter("cpassword");
		int customerSex = Integer.parseInt(request.getParameter("csex"));
		String customerTel = request.getParameter("ctel");
		String customerAdress = request.getParameter("cadress");
		BigDecimal customerProId = new BigDecimal(request.getParameter("cpid"));
		int isDelete=Integer.parseInt(request.getParameter("isDelete"));
		int roleMark=Integer.parseInt(request.getParameter("roleMark"));
		CustomerPOJO pojo = new CustomerPOJO(customerId, customerName,password,customerSex,customerTel,customerAdress,customerProId, isDelete, roleMark);
		System.out.println("输出数据:"+pojo.toString());
		boolean flag = CustomerDAOFactory.getDAOInstance().doUpd(pojo);
		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append(flag);
		out.print(sb.toString());
		out.close();
	}

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

}

DelCustomer   客户数据删除(伪删除,使数据不可见,方便误删找回)

public class DelCustomer extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		BigDecimal customerId = new BigDecimal(request.getParameter("customerId"));
		boolean flag = CustomerDAOFactory.getDAOInstance().doDel(customerId);
		System.out.println(flag);
		out.print(flag);
		out.close();
	}

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

}

FindCustomerById  查询客户,用于更新用户信息

public class FindCustomerById extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);

	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		BigDecimal cID = new BigDecimal(request.getParameter("cid"));
		CustomerPOJO pojo = CustomerDAOFactory.getDAOInstance().findById(cID);
		request.setAttribute("pojo", pojo);
		request.getRequestDispatcher("/manager/updateCustomer.jsp").forward(request, response);

	}
}

JDBCHelper 数据库辅助:

public class JDBCHelper {
	public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
	public static final String URL = "jdbc:oracle:thin:@localhost:1521:xxx";
	public static final String DBNAME = "name";
	public static final String PASSWORD = "xddd";
	public static Connection getConn() throws Exception{
		Class.forName(DRIVER);
		Connection conn = DriverManager.getConnection(URL, DBNAME, PASSWORD);
		return conn;

	}
}

AddCustomer.jsp   新增客户页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>新增客户</title>
    <script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.js"></script>
  </head>

  <body>
	<center>
		<h2>新增客户</h2>
		<hr/>
		<form name = "cus">
			客户名称:<input type="text" name="cname"/>
			<br/>
			<a style="float:left">客户性别:</a><select name="csex">
						<option value="0" selected="selected">女</option>
						<option value="1">男</option>
					</select>
			<br/>
			联系方式:<input type="text" name="ctel"/>
			<br/>
			客户住址:<input type="text" name="cadress"/>
			<br/>
			购买产品id:<input type="text" name="cpid"/>
			<br/>
			<input type="button" value="确认" onclick="add()"/>
			<input type="reset" value="重置" />
			<input type="button" value="返回" onclick="back()"/>
		</form>
	</center>
  </body>
  <script type="text/javascript">
		function add(){
			var cname=cus.cname.value;
			var csex=cus.csex.value;
			var ctel=cus.ctel.value;
			var cadress=cus.cadress.value;
			var cpid=cus.cpid.value;
			 $(document).ready(function(){
			 	//设置提交的路径,和参数
				$.post("<%=path%>/AddCustomer",
				{"cname":cname,"csex":csex,"ctel":ctel,"cadress":cadress,"cpid":cpid},
				function(data){//Servlet执行完之后执行方法,data表示的servlet返回数据内容
	 				if(data == "true"){
	 					alert("客户新增成功");
	 					back();
	 				}else{
	 					alert("客户新增失败,请联系系统管理员");
	 				}
	 			});
			});
		}

		function back(){
			opener.location.reload();
			//window.dialogArguments.query(0);//刷新之前页面
			window.close();//关闭当前页面
		}
	</script>
</html>

queryCustomer.jsp   客户查询删除页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>查询客户</title>
    <script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.js"></script>
  </head>

  <body>
	<form name = "que">
		<fieldset title="查询">
			<legend>
				<span width="12%" height="25" class="STYLE1"
								style="color: black;">查询条件</span>
			</legend>
			<input type="text" name="customer"/>
			<input type="button" value="查询客户ID" onclick="queryById(0)"/>
			<input type="button" value="查询客户姓名" onclick="queryByName(0)"/>
			<input type="button" value="显示所有客户资料" onclick="query(0)"/>
			<input type="button" value="新增" onclick="goAdd()"/>
		</fieldset>

		</form>
		<div id="showTable"></div>
		</body>
		<script type="text/javascript">
		var pageSize = 10;//一页显示的数据笔数
		var pageCurrent = 1;//显示的页数
		var allCount = 0;//总共的数据笔数
		var allPage = 0;//总共数据页数
		query(0);
		function query(num){
			if(num == 1){//第一页
				pageCurrent = 1;
			}else if(num == 2){//上一页
				pageCurrent = pageCurrent -1;
			}else if(num == 3){//下一页
				pageCurrent = pageCurrent + 1;
			}else if(num == 4){//最后一页
				pageCurrent = allPage;
			}
			 $(document).ready(function(){
			 	//设置提交的路径,和参数
				$.post("<%=path%>/CustomerQuery",{"pageSize":pageSize,"pageCurrent":pageCurrent},
				function(data){//Servlet执行完之后执行方法,data表示的servlet返回数据内容
	 				$("#showTable").html(data);//显示Servlet返回的内容
	 				controlButton();
	 			});
			});
		}
		function controlButton(){//设置按钮可见与否,停在第一页时不能点击上一页。停在最后一页时,不能点击下一页
			allCount = $("#count").val();
			if(allCount%pageSize == 0){
				allPage = allCount/pageSize
			}else{
				allPage = Math.floor(allCount/pageSize) +1;
			}
			document.getElementById("first").disabled = false;
			document.getElementById("up").disabled = false;
			document.getElementById("next").disabled = false;
			document.getElementById("end").disabled = false;
			if(allPage == 1){
				document.getElementById("first").disabled = true;
				document.getElementById("up").disabled = true;
				document.getElementById("next").disabled = true;
				document.getElementById("end").disabled = true;
			}else if(pageCurrent == 1){
				document.getElementById("first").disabled = true;
				document.getElementById("up").disabled = true;
			}else if(pageCurrent == allPage){
				document.getElementById("next").disabled = true;
				document.getElementById("end").disabled = true;
			}
			$("#showPageMessage").html("总共"+allCount+"笔数据,当前显示"+pageCurrent+"页,共"+ allPage+"页");

		}
			function goAdd(){
				var width = window.screen.width ;
				var height = window.screen.height ;
				window.open("<%=path%>/manager/addCustomer.jsp","新增客户",'height=400,width=300,top='+(height-450)/2+',left='+(width-300)/2+',toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');
			}
			function queryById(){
				var customerId = que.customer.value;
				 $(document).ready(function(){
				 	//设置提交的路径,和参数
					$.post("<%=path%>/CustomerQuery",{"customerId":customerId},
					function(data){//Servlet执行完之后执行方法,data表示的servlet返回数据内容
		 				$("#showTable").html(data);//显示Servlet返回的内容
		 			});
				});
			}
			function queryByName(){
				var customerName = que.customer.value;
				 $(document).ready(function(){
				 	//设置提交的路径,和参数
					$.post("<%=path%>/CustomerQuery",{"customerName":customerName},
					function(data){//Servlet执行完之后执行方法,data表示的servlet返回数据内容
		 				$("#showTable").html(data);//显示Servlet返回的内容
		 			});
				});
			}
			function goUpdate(customerId){
				var width = window.screen.width ;
				var height = window.screen.height ;
				window.open("<%=path%>/FindCustomerById?cid="+customerId,"修改客户",'height=400,width=300,top='+(height-450)/2+',left='+(width-300)/2+',toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');
			}
			function goDelete(customerId){
				if(confirm("确认删除?")){
					 $(document).ready(function(){
				 	//设置提交的路径,和参数
					$.post("<%=path%>/DelCustomer",{"customerId":customerId},
					function(data){
						//Servlet执行完之后执行方法,data表示的servlet返回数据内容
		 				if(data == "true"){
		 					alert("删除成功");
		 					query(0);
		 				}else{
		 					alert("删除失败,请联系系统管理员");
		 				}
		 			});
				});
				}
			}
		</script>
</html>

updateCustomer.jsp  更新客户信息界面:

<%@page import="org.jvsun.pojo.CustomerPOJO"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>更新客户</title>
    <script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.js"></script>
  </head>

  <body><%--
  <%
  	CustomerPOJO pojo=new CustomerPOJO();
  	int sex=pojo.getCustomerSex();
  	System.out.println(sex);
  	String str="";
  	if(sex==1){
  		str="男";
  	}else{
  		str="女";
  	}
  %>
	--%><center>
		<h2>更新客户</h2>
		<hr/>
		<form name = "cus">
			<input type="hidden" name="cid" value = "${pojo.customerId}"/>
			<br/>
			客户名称:<input type="text" name="cname" value = "${pojo.customerName}"/>
			<br/>
			客户密码:<input type="text" name="cpassword" value = "${pojo.password}"/>
			<br/>
			客户性别:<input type="text" name="csex" value = "${pojo.customerSex}"/>
			<br/>
			联系方式:<input type="text" name="ctel" value = "${pojo.customerTel}"/>
			<br/>
			客户住址:<input type="text" name="cadress" value = "${pojo.customerAdress}"/>
			<br/>
			购买产品id:<input type="text" name="cpid" value = "${pojo.customerProId}"/>
			<br/>
			客户状态:<input type="text" name="isDelete" value = "${pojo.isDelete}"/>
			<br/>
			客户标识:<input type="text" name="roleMark" value = "${pojo.roleMark}"/>
			<br/>
			<input type="button" value="确认" onclick="upd()"/>
			<input type="button" value="返回" onclick="back()"/>
		</form>
	</center>
  </body>
  <script type="text/javascript">
		function upd(){
			var cid=cus.cid.value;
			var cname=cus.cname.value;
			var cpassword=cus.cpassword.value;
			var csex=cus.csex.value;
			var ctel=cus.ctel.value;
			var cadress=cus.cadress.value;
			var cpid=cus.cpid.value;
			var isDelete=cus.isDelete.value;
			var roleMark=cus.roleMark.value;
			 $(document).ready(function(){
			 	//设置提交的路径,和参数
				$.post("<%=path%>/CustomerUpd",
				{"cid":cid,"cname":cname,"cpassword":cpassword,"csex":csex,"ctel":ctel,"cadress":cadress,"cpid":cpid,"isDelete":isDelete,"roleMark":roleMark},
				function(data){//Servlet执行完之后执行方法,data表示的servlet返回数据内容
	 				if(data == "true"){
	 					alert("客户修改成功");
	 					back();
	 				}else{
	 					alert("客户修改失败,请联系系统管理员");
	 				}
	 			});
			});
		}

		function back(){
			opener.location.reload();
			//window.dialogArguments.query(0);//刷新之前页面
			window.close();//关闭当前页面
		}
	</script>
</html>

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <servlet-name>AddCustomer</servlet-name>
    <servlet-class>org.jvsun.servlet.AddCustomer</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>CustomerQuery</servlet-name>
    <servlet-class>org.jvsun.servlet.CustomerQuery</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>CustomerUpd</servlet-name>
    <servlet-class>org.jvsun.servlet.CustomerUpd</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>DelCustomer</servlet-name>
    <servlet-class>org.jvsun.servlet.DelCustomer</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>FindCustomerById</servlet-name>
    <servlet-class>org.jvsun.servlet.FindCustomerById</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>AddCustomer</servlet-name>
    <url-pattern>/AddCustomer</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>CustomerQuery</servlet-name>
    <url-pattern>/CustomerQuery</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>CustomerUpd</servlet-name>
    <url-pattern>/CustomerUpd</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DelCustomer</servlet-name>
    <url-pattern>/DelCustomer</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>FindCustomerById</servlet-name>
    <url-pattern>/FindCustomerById</url-pattern>
  </servlet-mapping>
</web-app>

好了,所有的代码都展示完了,说这么多 就想知道谁有好的分页工具类能分享一下嘛,以后就能偷个懒了

时间: 2024-09-09 05:43:26

Java如何实现后端分页的相关文章

js分页-java js完整版分页后台

问题描述 java js完整版分页后台 求完整版js分页代码,最好是从action中带参数的用hibernate分页 解决方案 用js插件........

Java Web 简单的分页显示实例代码_java

本文通过两个方法:(1)计算总的页数. (2)查询指定页数据,实现简单的分页效果. 思路:首先得在 DAO 对象中提供分页查询的方法,在控制层调用该方法查到指定页的数据,在表示层通过 EL 表达式和 JSTL 将该页数据显示出来. 先给大家展示下效果图: 题外话:该分页显示是用 "表示层-控制层-DAO层-数据库"的设计思想实现的,有什么需要改进的地方大家提出来,共同学习进步.废话不多说了,开始进入主题,详细步骤如下所示: 1.DAO层-数据库 JDBCUtils 类用于打开和关闭数据

java开发中通用分页类代码

java开发中通用分页类代码 在java中要分页我们必须要有数据库教程,所以我们先准备下数据库,其数据库脚步如下: --以下是创建数据库和数据库表以及向数据库插入数据   use master  Go  if exists(select * from sysdatabases where name='pagination')  drop database pagination  Go  create database pagination  Go  use pagination  Go  cre

使用Jquery+Ajax+Json如何实现分页显示附JAVA+JQuery实现异步分页_AJAX相关

先给大家展示下运行效果图:  1.后台action产生json数据. List blackList = blackService.getBlackInfoList(mobileNum, gatewayid, startDate, endDate); int totalRows = blackList.size(); StringBuffer sb = new StringBuffer(); sb.append("{\"totalCount\":\""+to

使用Jquery+Ajax+Json如何实现分页显示附JAVA+JQuery实现异步分页

先给大家展示下运行效果图: 1.后台action产生json数据. List blackList = blackService.getBlackInfoList(mobileNum, gatewayid, startDate, endDate); int totalRows = blackList.size(); StringBuffer sb = new StringBuffer(); sb.append("{\"totalCount\":\""+tot

分页技术原理与实现之Java+Oracle代码实现分页(二)_java

紧接着上篇-分页技术原理与实现之分页的意义及方法(一) ,本篇继续分析分页技术.上篇讲的是分页技术的简单原理与介绍,这篇深入分析一下分页技术的代码实现. 上篇最后讲到了分页的最佳实现是在数据库层进行分页,而且不同的数据库有不同的分页实现,比如Oracle是用三层sql嵌套实现分页的.MySQL是用limit关键字实现的(上篇已讲到). 这篇以Java+Oracle为基础,讲解代码层的实现. 就如平时我们很在分页中看到的,分页的时候返回的不仅包括查询的结果集(List),而且还包括总的页数(pag

【java】itext pdf 分页

importjava.io.FileOutputStream;   importcom.lowagie.text.Document; importcom.lowagie.text.Element; importcom.lowagie.text.ExceptionConverter; importcom.lowagie.text.Font; importcom.lowagie.text.PageSize; importcom.lowagie.text.Paragraph; importcom.lo

网页的分页下标生成代码(PHP后端方法)_php实例

测试图例: 效果图: 实现代码: /** * * @param $page 页码(1至正无穷) * @param $num 数据中多上行为一页 * @param $rows 数据的总行数 * @param $length 下标的最大长度 * @return array */ public function PageDate($page, $num , $rows , $length){ //初始化数据 $MaxPage = 0; //最大页码 $MinPage = 0; //最小页码 $Serv

c++-java前端和java后端区别

问题描述 java前端和java后端区别 虽说有c++基础,但是对Java不甚了解.小虾再次请教各位大神,Java前端跟后端的区别在哪里?还有若同是架构,Java和c++区别在哪呢? 跪求大神们回答简单明了些哈,小妹很笨的(*^__^*) 嘻嘻-- 解决方案 至于区别: 底层的应用采取C++开发比较适合,例如:一些驱动,图像处理, 3d游戏之类的. java的话,比如web应用,还有目前比较火的android 手机 pad 应用等, 相对来说 java比较简单一些. 优缺点的话: c++写的程序