JDBC学生管理系统--处理分页显示

分页的思想:

假设一共有104条数据,每页显示10条数据:

select * from student limit 0,10;

页数是index,第index页,对应的sql语句是:

select * from student limit (index-1) * 10, 10;

页面上需要的数据: 第n页 / 共m页    上一页  第 1  2  3   4   5   6 页  下一页   跳转到第n页   选择第n页  


 

需要创建一个类Page来存放分页的数据:

 

package student.web.formbean;

import java.io.Serializable;
import java.util.List;

import student.bean.Student;

public class Page implements Serializable{

    private int currentPageIndex; //当前页的索引
    
    private int pageCount;  //共有多少页
    
    private int count = 10;   //每一页显示的数据
    
    private int totalDataCount; //表中共有多少条数据
    
    private int startIndex = 1; //页面索引的起始索引
    
    private int endIndex = 5; //页面的结束索引
    
    //增加一个页面上要显示的所有的数据的集合
    private List<Student> list;
    
    public List<Student> getList() {
        return list;
    }

    public void setList(List<Student> list) {
        this.list = list;
    }

    public Page(int totalCount, int count){
        this.totalDataCount = totalCount;
        this.count = count;
        //计算有多少页
        pageCount = (totalCount + count - 1) /count;
    }

    public int getCurrentPageIndex() {
        return currentPageIndex;
    }

    public void setCurrentPageIndex(int currentPageIndex) {
        this.currentPageIndex = currentPageIndex;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTotalDataCount() {
        return totalDataCount;
    }

    public void setTotalDataCount(int totalDataCount) {
        this.totalDataCount = totalDataCount;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }

    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }
}

 

cellphone数据类型最好都是String类型。

 

然后改造StudentDaoImpl中的listAll  ,将原来的listAll 废弃掉 @Deprecated  

package student.dao;

import java.util.List;

import student.bean.Student;

public interface StudentDao {

    /**
     * 添加一个学生
     * @param student
     * @return
     */
    public boolean add(Student student);
    
    /**
     * 删除一个学生
     * @param id
     * @return boolean
     */
    public boolean delete(String id);
    
    /**
     * 更新
     * @param student
     * @return
     */
    public boolean update(Student student);
    
    /**
     * 获取所有的学生
     * @return
     */
    @Deprecated   //废弃的方法
    public List<Student> getAllStudent();
    
    /**
     * 根据客户的编号查询客户
     * @param id
     * @return 成功则返回此用户,否则返回null
     */
    public Student findStudentById(String id);
    
    /**
     * 根据页面的索引查询此页面的数据
     * @param currentPageIndex  当前页的索引
     * @param count 每页要显示的记录数
     * @return 返回次页面的一个集合
     */

    //新增加的方法
public List<Student> getPageList(int currentPageIndex,int count); /** * 获取数据的个数 * @return 返回表中数据的数量 */ public int getTotalCount(); }

 

 修改StudentDao.java方法

 

@Override
    public List<Student> getPageList(int currentPageIndex, int count) {
                //拿到连接对象
                Connection conn = JdbcUtils.getConnection();
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                List<Student> list = new ArrayList<Student>();
                //创建预处理命令对象
                
                try {
                    pstmt = conn.prepareStatement("select id,name,gender,birthday,cellphone,email,hobby,type,description from student limit ?,?");
                    //执行sql语句
                    pstmt.setInt(1 ,(currentPageIndex-1)*count);
                    pstmt.setInt(2, count);
                    rs = pstmt.executeQuery();
                    System.out.println("---rs---" + rs);
                    /**
                     *  ResultSet 光标最初位于第一行之前;第一次调用 next 方法使第一行成为当前行;第二次调用使第二行成为当前行,依此类推。 
                     *  当调用 next 方法返回 false 时,光标位于最后一行的后面。任何要求当前行的 ResultSet 方法调用将导致抛出 SQLException。
                     */
                    while(rs.next()){
                        //封装数据, 在service中将数据封装到page对象的list中
                        Student s = new Student();
                        try {
                            //指定编码,否则在网络传输中会出错
                            String id = URLEncoder.encode(rs.getString("id"),"UTF-8");
                            s.setId(id);
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        s.setName(rs.getString("name"));
                        s.setGender(rs.getString("gender"));
                        s.setBirthday(rs.getDate("birthday"));
                        s.setCellphone(rs.getString("cellphone"));
                        s.setEmail(rs.getString("email")) ;
                        s.setHobby(rs.getString("hobby")) ;
                        s.setType(rs.getString("type")) ;
                        s.setDescription(rs.getString("description")) ;
                        
                        list.add(s);
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    JdbcUtils.release(rs, pstmt, conn);
                }
                
                return list;
    }

    @Override
    public int getTotalCount() {
        //拿到连接对象
        Connection conn = JdbcUtils.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        //创建预处理命令对象
        try {
            pstmt = conn.prepareStatement("select count(*) from student");
            //执行sql语句
            rs = pstmt.executeQuery();
            /**
             *  ResultSet 光标最初位于第一行之前;第一次调用 next 方法使第一行成为当前行;第二次调用使第二行成为当前行,依此类推。 
             *  当调用 next 方法返回 false 时,光标位于最后一行的后面。任何要求当前行的 ResultSet 方法调用将导致抛出 SQLException。
             */
            while(rs.next()){
                return rs.getInt(1);
                
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JdbcUtils.release(rs, pstmt, conn);
        }
        
        return 0;
    }

}

 

 然后改造ServiceDao,需要将dao层获取的数据都放到Page对象中,然后从page中拿取: (新添加的方法)

/**
* 根据传递过来的索引数和每页显示的数据确定当前页的数据
* @param currentPageIndex 索引页
* @param count 每页的数据
* @return
*/
public Page getPageList(int currentPageIndex, int count);

/**
* 得到数据库中所有的数据的条数
* @return
*/
public int getTotalCount();

/**
*
* 得到页面的数量
* @param count
* @return
*/
public int getPageCount(int count);  //用在Controller.java中因为页面需要单独获取数据库中的总数目(页数)

 

修改ServiceDaoImpl.java

    @Override
    public Page getPageList(int currentPageIndex, int count) {
        //获取总的数据的个数
        int totalCount = sd.getTotalCount();
        //创建并初始化Page对象
        Page page = new Page(totalCount,count);
        //给page中的currentPageIndex赋值。
        page.setCurrentPageIndex(currentPageIndex);
        //获取数据
        page.setList(sd.getPageList(currentPageIndex, count));
        return page;
        
    }

    @Override
    public int getTotalCount() {
        return sd.getTotalCount();
    }

  @Override
  public int getPageCount(int count) {
    int totalCount = sd.getTotalCount();
    return (totalCount + count - 1) /count;
  }

 

 

修改 Controller.java 控制


package student.web.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;


import student.bean.Student;
import student.service.StudentService;
import student.service.impl.StudentServiceImpl;
import student.utils.WebTools;
import student.utils.WebUtils;
import student.web.formbean.Page;
import student.web.formbean.StudentFromBean;


public class Controller extends HttpServlet {


StudentService ss = new StudentServiceImpl();
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/

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


request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//拿到页面传递的数据
String op = request.getParameter("op");
System.out.println("--op--" + op);
//根据页面数据做判断
if("all".equals(op)){
listAll(request,response);
}else if("add".equals(op)){
addStudent(request,response);
}else if("update".equals(op)){
update(request,response);
}else if("delete".equals(op)){
delete(request,response);
}else if("delmore".equals(op)){
delmore(request,response);
}else if("toupdate".equals(op)){
toupdate(request,response);
}else if("page".equals(op)){
listpage(request,response);
}
}


private void listpage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
//拿到页面传递的页面索引
String currentPageIndex = request.getParameter("currentPageIndex");
System.out.println("get currentPageIndex=" + currentPageIndex);
//给session中设置两个属性,记录循环开始结束的值
HttpSession session = request.getSession();
//调用service层查询第一页的数据
//需要将string类型转换成int类型
int pageIndex = Integer.parseInt(currentPageIndex);
//首先查询需要多少页
int pageCount = ss.getPageCount(10);//因为这个时候还没有创建page对象,所以只能先用这个方法得到页面的数
System.out.println("------------pageCount="+pageCount);
if(pageIndex < 1){
pageIndex = 1;
}
if(pageIndex > pageCount){
pageIndex = pageCount;
}
//这一步没有设定每一页应该显示的数据是多少,可以然后再页面上重新设定该参数。
Page page = ss.getPageList(pageIndex, 10);
//根据传递的索引页来判断是否需要改变page队形的startIndex,endIndex
//判断是不是两个·极端
/* 这个方法不可行,需要使用session来保存已有的数值
if(pageIndex == page.getStartIndex() && pageIndex != 1){
//最左边
page.setStartIndex(page.getStartIndex() - 1);
page.setEndIndex(page.getEndIndex() - 1);
}

if(pageIndex == page.getEndIndex() && pageIndex != pageCount){
//最右边
page.setStartIndex(page.getStartIndex() + 1);
page.setEndIndex(page.getEndIndex() + 1);
}
*/

/**
* 由于每次点击都会产生一个新的pageIndex对象,对象中的startIndex和endIndex都会恢复到1,5,不能保存上次的page对象
* 需要给session中设置属性,记录循环的开始和结束的值
*/

Integer start = (Integer)session.getAttribute("startIndex");
Integer end = (Integer)session.getAttribute("endIndex");
if(start == null){
session.setAttribute("startIndex", 1);
}
if(end == null){
if(pageCount < 5){
session.setAttribute("endIndex", 5);
}
session.setAttribute("endIndex", 5);
}

if(pageIndex == (Integer)session.getAttribute("startIndex") && pageIndex != 1){
//点击最左边的页数
session.setAttribute("startIndex", (Integer)session.getAttribute("startIndex") - 1);
session.setAttribute("endIndex", (Integer)session.getAttribute("endIndex") - 1);
}

if(pageIndex == (Integer)session.getAttribute("endIndex") && pageIndex != pageCount){
//最右边的页数
session.setAttribute("startIndex", (Integer)session.getAttribute("startIndex") + 1);
session.setAttribute("endIndex", (Integer)session.getAttribute("endIndex") + 1);
}

if(pageIndex < (Integer)session.getAttribute("startIndex") ){
System.out.println("pageIndex < startIndex =" +pageIndex);
if(pageIndex == 1){//如果等于1,那就不需要再减少一个了
session.setAttribute("startIndex", pageIndex);
session.setAttribute("endIndex", pageIndex + 3);
}else{
//最右边
session.setAttribute("startIndex", pageIndex - 1);
session.setAttribute("endIndex", pageIndex + 3);
}

}

if(pageIndex > (Integer)session.getAttribute("endIndex") ){
//最右边
if(pageIndex == 10){
session.setAttribute("startIndex", pageIndex - 3 );
session.setAttribute("endIndex", pageIndex);
}else{
session.setAttribute("startIndex", pageIndex - 3);
session.setAttribute("endIndex", pageIndex + 1);
}
}

//接着,将page对象存入session中
request.getSession().setAttribute("page", page);
response.sendRedirect(request.getContextPath() + "/list.jsp");
}


private void toupdate(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 封装页面传递过来的数据
//封装页面数据
StudentFromBean sfb = WebUtils.fillFormBean(StudentFromBean.class, request);
System.out.println("---formbean---" + sfb.toString());
//检测数据
System.out.println("===validate===" + sfb.validate());
if(sfb.validate()){
//验证通过,将forbean中的数据拷贝到javabean中
Student s = new Student();
//由于时间是date类型,需要注册一个时间转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
try {
BeanUtils.copyProperties(s, sfb);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("---update封装了进来的数据---" + s);
//根据formbean对象的id来封装数据,应该是已经封装进来了
// s.setId(WebTools.createNewId());
//其次由于hobby的类型不同,所以不会拷贝数据,需要收到拷贝
//拿到页面的爱好数组,将数组拼接成一个字符串
String[] hobby = sfb.getHobby();
if(hobby != null && hobby.length > 0){
StringBuffer sf = new StringBuffer(hobby[0]);
for (int i = 1; i < hobby.length; i++) {
sf.append("," + hobby[i]);
}
s.setHobby(sf.toString());
}
//此时应该是已经封装完成了 student对象s
System.out.println("---封装了全部数据,准备写入数据库---" + s);
//调用service层完成业务逻辑,更新数据

boolean flag = ss.update(s);
if(flag){
//说明添加成功,转向主页面,
//先重新查询数据库,拿取数据后在转向主页
listpage(request,response); //此处不用listAll ,使用listpage()时要注意将页面上的currenPageIndex传递过来
}else{
//添加失败
request.setAttribute("errors", "修改失败");
request.getRequestDispatcher(request.getContextPath() + "/update.jsp");
}
}else{
//验证失败,踢回去,sfb对象存入request对象中,错误信息显示到页面上
//算是数据回显
request.setAttribute("user", sfb);
//给页面传递的
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
}


private void delmore(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获取传递的ids
String all = request.getParameter("ids");
System.out.println("--all---" + all);
//由于ids后面多了一个逗号,记得去掉 ----> 测试没有这一步也没有问题
//ids = ids.substring(0, ids.length()-1) ;
//拿到了ids,拆分后多次调用
String [] ids = all.split(",") ;
for (int i = 0; i < ids.length; i++) {
System.out.println("id" +i+"---"+ ids[i]);
if(!ss.delete(ids[i])){
//删除失败
request.getSession().setAttribute("error", "删除失败");
System.out.println("删除失败");
}
}
//listAll(request, response);
listpage(request,response);
}


private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//根据id删除对应的行
String id = request.getParameter("id");
System.out.println("--id--" + id);
System.out.println("getparameter -currentPageIndex" + request.getParameter("currentPageIndex"));
//拿到了页面传递过来的id,根据id来删除用户
if(!ss.delete(id)){
//删除失败
request.getSession().setAttribute("error", "删除失败");
}
//listAll(request, response);
listpage(request,response);
}


private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//获取id
String id = request.getParameter("id");
//根据id来更新内容
//根据id找到该用户,将该用户信息发送到更新页面上,提交到数据库
System.out.println("--update--" + id);
Student s = ss.findStudentById(id);
System.out.println("--find--" + s);
if(s != null){
//请求重定向,必须存放到session中,为什么不使用重定向 ??? 拭目以待
request.getSession().setAttribute("s", s);
// response.sendRedirect(request.getContextPath() + "/update.jsp");
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
}


private void addStudent(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {


//封装页面数据
StudentFromBean sfb = WebUtils.fillFormBean(StudentFromBean.class, request);
System.out.println("---formbean---" + sfb.toString());
//检测数据
System.out.println("===validate===" + sfb.validate());
if(sfb.validate()){
//验证通过,将forbean中的数据拷贝到javabean中
Student s = new Student();
//由于时间是date类型,需要注册一个时间转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
try {
BeanUtils.copyProperties(s, sfb);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("---封装了一部分内容---" + s);
//此时的s对象中没有id属性,需要通过一个类来生成id
s.setId(WebTools.createNewId());
//其次由于hobby的类型不同,所以不会拷贝数据,需要收到拷贝
//拿到页面的爱好数组,将数组拼接成一个字符串
String[] hobby = sfb.getHobby();
if(hobby != null && hobby.length > 0){
StringBuffer sf = new StringBuffer(hobby[0]);
for (int i = 1; i < hobby.length; i++) {
sf.append("," + hobby[i]);
}
s.setHobby(sf.toString());
}
//此时应该是已经封装完成了 student对象s
System.out.println("---封装了全部数据,准备写入数据库---" + s);
//调用service层完成业务逻辑
boolean flag = ss.add(s);
if(flag){
//说明添加成功,转向主页面,
//先重新查询数据库,拿取数据后在转向主页
//listAll(request, response);
listpage(request,response);
}else{
//添加失败
request.setAttribute("errors", "添加失败");
request.getRequestDispatcher(request.getContextPath() + "/add.jsp");
}
}else{
//验证失败,踢回去,sfb对象存入request对象中,错误信息显示到页面上
//算是数据回显
request.setAttribute("user", sfb);
//给页面传递的
request.getRequestDispatcher("/add.jsp").forward(request, response);

}
}


private void listAll(HttpServletRequest request,
HttpServletResponse response) throws IOException {


//显示所有的数据
//拿到所有的数据
/**
* 分层思想,表现层调用业务逻辑层来完成,不需要管他们怎么实现。
*/
// List<Student> list = ss.getAllStudent();
Page page = ss.getPageList(1, 10);
//将数据存放到session中
/**
* 为什么要放到session中而不是request中 ?
* 这个地方如果采用请求转发,增加或改动之后,就会转发到这里来重新查询,但是当转发过来之后,又是一次。算了,自己试一次就知道了。
*
*
* 重定向和转发有一个重要的不同:当使用转发时,JSP容器将使用一个内部的方法来调用目标页面,新的页面继续处理同一个请求,而浏览器将不会知道这个过程。
* 与之相反,重定向方式的含义是第一个页面通知浏览器发送一个新的页面请求。因为,当你使用重定向时,浏览器中所显示的URL会变成新页面的URL,
* 而当使用转发时,该URL会保持不变。重定向的速度比转发慢,因为浏览器还得发出一个新的请求。同时,由于重定向方式产生了一个新的请求,所以经过一次重 定向后,
* request内的对象将无法使用。 怎么选择是重定向还是转发呢?通常情况下转发更快,而且能保持request内的对象,所以他是第一选择。但是由于在转发之后,
* 浏览器中URL仍然指向开始页面,此时如果重载当前页面,开始页面将会被重新调用。如果你不想看到这样的情况,则选择转发。
*/

//请求重定向,必须存放到session中
request.getSession().setAttribute("page", page);
response.sendRedirect(request.getContextPath() + "/list.jsp");
}



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


doGet(request, response);
}


}

 

 

修改list.jsp页面      

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%
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>
<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>
<style type="text/css">
#t1{
width=900px;
}
#t2{
border:1px solid gray;
border-collapse: collapse <!--表格的边框合并成一个单一的边框 -->
font-size:15px;
text-align:center;
}
#t2 td,tr,th{
border:1px,solid gray
}
#t2 tr:hover{
background-color: ffccff; <!-- 鼠标移动后变色 -->
}

a{
text-decoration: none;
}

</style>
<script type="text/javascript">
/* 对于javascript很不了解,需要重新学习javascript视频 */
function checkAll(flag){
//拿到所有的记录
alert(flag);
var ids = document.getElementsByName("ids");
//循环设置每一个复选框
for (var i = 0; i < ids.length; i++) {
ids[i].checked = flag;
}
}

function delmore(){
//拿到所有的记录的复选框
var ids =document.getElementsByName("ids");
//构建id字符串,循环判断每一个复选框是否选中
var s = "";
for(var i = 0; i <ids.length; i++){
if(ids[i].checked == true){
//拿到复选框的value
s += ids[i].value + ",";
}
}
//数据传递到服务端进行删除
window.location = "${pageContext.request.contextPath}/servlet/Controller?op=delmore&ids=" + s + "&currentPageIndex=${page.currentPageIndex}"; //此处要加上当前页数,通过pagelist(request,response) 函数查询时还是要返回当前页
}
/* 现在开始写javascript代码,给跳转用 */
/* 两种情况:1.输入第几页,然后点击跳转; 2.点击下拉框跳转到指定页面 */
function jump(index){
/* 需要判断是从超链接过来的还是select过来的,方法 : alert(index); 看参数是什么 ,页面提示undefined*/
/* alert(index); */
if("undefined" == typeof(index) ){
//需要拿到文本框中的超链接 ,根据id来拿
/* alert("index"); */
var n = document.getElementById("pageIndex").value;
/* alert(n); */
//判断拿到的内容是否为数字
if(isNaN(n) ){
alert("必须填写数字");
return;
}
if(n == ""){
alert("不能为空");
return;
}
index = n;
}
window.location.href="${pageContext.request.contextPath}/servlet/Controller?op=page&currentPageIndex=" + index;
}

</script>
<body>
学生管理系统 <br>
<h1 align="center">学生信息</h1>
<hr>
<font color =red>${error }</font>
<table id="t1" border=1>
<tr>
<td>
<a href="${pageContext.request.contextPath }/add.jsp">添加</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="javascript:delmore()">删除</a>
</td>
</tr>
<tr>
<td>
<table id = "t2" width="100%"> <!-- 占据单元格的100% -->
<tr>
<th><input type="checkbox" id="all" onclick="checkAll(this.checked)">全选全不选</th>
<th>姓名</th>
<th>性别</th>
<th>生日</th>
<th>电话</th>
<th>邮箱</th>
<th>爱好</th>
<th>类型</th>
<th>描述</th>
<th>操作</th>
</tr>
<c:choose>
<c:when test="${empty page.list}">
<tr>
<td colspan="10" align = "center">暂时没有数据</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach items="${page.list}" var="c">
<tr>
<td><input type="checkbox" name="ids" value="${c.id }"></td>
<td>${c.name }</td>
<td>${c.gender == "1" ? "男" : "女"}</td>
<td>${c.birthday }</td>
<td>${c.cellphone }</td>
<td>${c.email }</td>
<td>${c.hobby }</td>
<td>${c.type == "vip" ? "贵宾" : "会员" }</td>
<td>${c.description }</td>
<td><a href="${pageContext.request.contextPath }/servlet/Controller?op=update&id=${c.id}">修改</a>&nbsp;&nbsp;&nbsp;<a href="${pageContext.request.contextPath }/servlet/Controller?op=delete&id=${c.id}&currentPageIndex=${page.currentPageIndex} ">删除</a></td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
</td>
</tr>
</table>
<table border=1>
<td width="20%"><font>&nbsp;第${page.currentPageIndex}页/共${page.pageCount}页</font></td>
<!-- 此时页面上显示的是第0页,是因为这个page对象中的currentPageIndex没有数据导致,所以需要给他赋值。需要在service中赋值。 -->
<td width="45%"><a href="${pageContext.request.contextPath}/servlet/Controller?op=page&currentPageIndex=${page.currentPageIndex-1}">|&lt</a>
<c:forEach begin="${startIndex}" end="${endIndex}" var = "n"><!-- 现在改成从session中拿取,不需要page对象了 -->
<a href="${pageContext.request.contextPath}/servlet/Controller?op=page&currentPageIndex=${n}">${page.currentPageIndex == n?"<font color=red>":"<font>"}${n}</font>&nbsp;</a>
</c:forEach>
<a href="${pageContext.request.contextPath}/servlet/Controller?op=page&currentPageIndex=${page.currentPageIndex + 1}">&gt|</a>
</td>
<!-- <td width="40%"></td> -->
<td width="20%"><input type="text" size="5" name="currentPageIndex" id="pageIndex"><a href="javascript:jump()">&nbsp;跳转&nbsp;&nbsp;</a></td>
<td width="20">
<select name="currentPageIndex" onchange="jump(this.value)">
<c:forEach begin="1" end="${page.pageCount}" var="n">
<option value="${n}" ${page.currentPageIndex == n?"selected":"" }>&nbsp;第${n}页</option>
</c:forEach>
</select>
</td>
</table>
</body>
</html>

 

index.jsp

 <a href="${pageContext.request.contextPath }/servlet/Controller?op=page&currentPageIndex=1">显示分页数据</a>

 update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fun" %>
<%
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>
    
    <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">
    -->

    <script type="text/javascript"
            src="${pageContext.request.contextPath }/js/Birthday-Calendar.js"></script>
  </head>
  
  <body>
    <h1 align="center">修改学生信息</h1>
    <hr>
    <form action="${pageContext.request.contextPath }/servlet/Controller?op=toupdate&currentPageIndex=${page.currentPageIndex}" method="post">
        <table align="center" border="1">
            <tr>
                <td align="left" colspan = "2"><input type="hidden" name="id" value="${s.id}"></td>
            </tr>
            <tr>
                <td align="right" width="40%">姓名</td>
                <td align="left"><input type="text" name="name" value="${s.name }"></td>
                <td ><font color="red">${user.errors.name}</font></td>
            </tr>
            <tr>
                <td align="right" width="40%">性别</td>
                <td align="left"><input type="radio" name="gender" value="1" ${s.gender == "1" ? "checked" : ""} >男<input type="radio" name="gender" value="0" ${s.gender == "0" ? "checked" : ""} >女</td>
            </tr>
            <tr>
                <td align="right" width="40%">生日</td>
                <td align="left"><input type="text" name="birthday" onfocus="new Calendar().show(this)" readonly="readonly" value="${s.birthday}"></td>
                <!-- 这一段不明白如何添加日期 -->
            </tr>
            <tr>
                <td align="right" width="40%">电话:</td>
                <td align="left"><input type="text" name="cellphone" value="${s.cellphone }"></td>
            </tr>
            <tr>
                <td align="right" width="40%">邮箱:</td>
                <td align="left"><input type="text" name="email" value="${s.email}"></td>
            </tr>
            <tr>
                <td align="right" width="40%">爱好</td><!-- 由于hobby传递过来的是一个字符串,所以: -->
                <td align="left"><input type="checkbox" name="hobby" value="骑行" ${fun:contains(s.hobby,"骑行")?"checked":""}>骑行<input type="checkbox" name="hobby" value="游泳" ${fun:contains(s.hobby,"游泳")?"checked":""}>游泳
                                 <input type="checkbox" name="hobby" value="看电影" ${fun:contains(s.hobby,"看电影")?"checked":""}>看电影</td>
            </tr>
            <tr>
                <td align="right" width="40%">类型</td>
                <td align="left"><input type="radio" name="type" value="vip" ${s.type == "vip" ? "checked" : "" }>贵宾<input type="radio" name="type" value="common" ${s.type == "common" ? "checked" : "" }>会员</td>
            </tr>
            <tr>
                <td align="right" width="40%">描述</td>
                <td align="left"><textarea rows="5" cols="20" name="description">${s.description}</textarea></td>
            </tr>
            <tr>
                <td align="center" colspan="2"><input type="submit" value="保存"></td>
            </tr>
        </table>
    </form>
  </body>
</html>

 


 

select * from student limit 0,10;  --检索记录1-10

LIMIT 子句可以被用于强制 SELECT 语句返回指定的记录数。LIMIT 接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1): 为了与 PostgreSQL 兼容,MySQL 也支持句法: LIMIT # OFFSET #。 

mysql> SELECT * FROM table LIMIT 5,10;  // 检索记录行 6-15

//为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1: 
mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.--测试mysql5.5不能用

//如果只给定一个参数,它表示返回最大的记录行数目: 
mysql> SELECT * FROM table LIMIT 5;     //检索前 5 个记录行

//换句话说,LIMIT n 等价于 LIMIT 0,n。

 

数据库中插入多条语句

package student.insert;

import java.util.Date;

import student.bean.Student;
import student.dao.StudentDao;
import student.dao.impl.StudentDaoImpl;
import student.utils.WebTools;

public class Insert {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        StudentDao dao = new StudentDaoImpl();
        
        for (int i = 0; i < 105; i++) {
            Student s = new Student();
            s.setId(WebTools.createNewId());
            s.setName("崔佛-菲利普" + (i + 1));
            s.setCellphone("138334512" + i);
            s.setBirthday(new java.sql.Date(new Date().getTime()));
            s.setEmail("崔佛-菲利普"+ i +"@163.com");
            s.setGender("1");
            s.setHobby("看电影");
            s.setType("vip");
            s.setDescription("一万年太久,只争朝夕");
            
            dao.add(s);
        }
    }
}

 

posted @ 2016-12-14 11:50  kangjie  阅读(1603)  评论(0编辑  收藏  举报