欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

程序员文章站 2022-04-04 21:41:31
下面以一个示例讲解如何使用MySQL+Service+Servlet+Jsp实现Table表格分页展示数据: eg:请假管理系统 要求如下: 一、打开首页页面, 访问查询请假记录的 servlet , 将查询结果在列表页面进行分页展并按照请假时同升序排序。整个页面的标题需要加粗加大显示,请假记录列表 ......

下面以一个示例讲解如何使用mysql+service+servlet+jsp实现table表格分页展示数据:

eg:请假管理系统

要求如下:

 一、打开首页页面, 访问查询请假记录的 servlet , 将查询结果在列表页面进行分页展并按照请假时同升序排序。整个页面的标题需要加粗加大显示,请假记录列表要求使用式实现对表头文字加粗显示, 超链接 (包括 “ 删除” 和 “ 添加请假记录” 两个) 无下划线且 ’添加请假记录“字体为红色, 并实现信息列表隔行变色显示, 程序运行界面下:

                    MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

      点击 “添加请假记录“ 进入添加请假记录页面;如下图所示:

                        MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

      

      点击”提交“按钮提交表单时.要求使用‘jquery对页面输入项进行验证.验证内包括姓名,请假shij、 请假原因的非空验证 ; 其中请假时间还必须进行格式验证 ,验证效果如下所示:

        MySQL+Service+Servlet+Jsp实现Table表格分页展示数据      

        MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

  

    表单数据通过验证后. 则提交请求至添加请假记录的 servlet:, 如添加成功,则给出成功提示,如下图:

                MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

      点击 ”确定’ 后跳转至请假记录信息的列表页面, 并非显示最新的请假记录信息, 效果如下所示:

              MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

     如果添加请假记录信息失败,同样给出添加失败提示,并跳转回添加请假记录页面,重新添加请假记录信息;

     当用户点击某一条请假记录信息对应的 “删除” 超链接时, 首先弹出信息提示框确认是否删除 , 效果如下图:

             MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

    当用户点击 “确定" 后, 实现请假讵录的删除操作, 要求使用ajax 异步请求后台sevlet 方法进行删除,最后给出删除成功或者失败的信息提示;

 二、mysql数据库设计如下:

    MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

三、项目分层设计如下:

          MySQL+Service+Servlet+Jsp实现Table表格分页展示数据        MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

项目代码如下:

 leaverecordsdao.java

package cn.jbit.leavereccords.dao;

import java.util.list;
import java.util.map;

import cn.jbit.leavereccords.entity.leaverecords;

public interface leaverecordsdao {
    /**
     * 删除请假信息
     * 
     * @param id
     * @return
     */
    public int deleteleaverecords(integer id);


    /**
     * 添加请假信息
     * 
     * @param leaverecords  请假信息的对象
     * @return
     */
    public int addleaverecords(leaverecords leaverecords);
    
    /**
     * 分页查询所有消息
     * @param pageindex 页码
     * @param pagesize 数据行数
     * @return 查询到的集合
     */
    public list<leaverecords> selecteleaverecords(int pageindex, int pagesize);
    
    /**
     * 查询总记录数
     * @return 查询到记录总数
     */
    public int count();
    
}

leaverecordsdaoimpl.java

package cn.jbit.leavereccords.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 java.util.map;

import cn.jbit.leavereccords.dao.basedao;
import cn.jbit.leavereccords.dao.leaverecordsdao;
import cn.jbit.leavereccords.entity.leaverecords;
import cn.jbit.leavereccords.util.databaseutil;

public class leaverecordsdaoimpl extends basedao implements leaverecordsdao {

    /**
     * 删除
     */
    @override
    public int deleteleaverecords(integer id) {
        int result = 0;
        string sql = "delete from leaverecords where id=?";
        try {
            result = this.executeupdate(sql, id);
        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return result;
    }

    @override
    public int addleaverecords(leaverecords leaverecords) {
        int result = 0;
        string sql = "insert into `leaverecords`(`name`,leavetime,reason) values (?,?,?)";
        try {
            result = this.executeupdate(sql, leaverecords.getname(), leaverecords.getleavetime(),
                    leaverecords.getreason());
        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return result;
    }

    /**
     * 分页显示数据
     */
    @override
    public list<leaverecords> selecteleaverecords(int pageindex, int pagesize) {
        string sql = "select id,`name`,leavetime,reason from leaverecords  order by leavetime asc limit ?,?";
        connection conn = null;
        preparedstatement pstmt = null;
        resultset rs = null;
        leaverecords records = null;
        list<leaverecords> leaverecordslist = new arraylist<leaverecords>();
        try {
            conn = databaseutil.getconnection();
            pstmt = conn.preparestatement(sql);
            pstmt.setint(1, (pageindex - 1) * pagesize);
            pstmt.setint(2, pagesize);
            rs = pstmt.executequery();
            while (rs.next()) {
                records = new leaverecords();
                records.setid(rs.getint("id"));
                records.setname(rs.getstring("name"));
                records.setleavetime(rs.getdate("leavetime"));
                records.setreason(rs.getstring("reason"));
                leaverecordslist.add(records);
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            databaseutil.closeall(conn, pstmt, rs);
        }
        return leaverecordslist;
    }

    /**
     * 查询总数
     */
    @override
    public int count() {
        int result = 0;
        string sql = "select count(1) from leaverecords";
        resultset rs = null;
        try {
            rs = this.executequery(sql);
            while (rs.next()) {
                result = rs.getint(1);
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            databaseutil.closeall(null, null, rs);
        }
        return result;
    }
}

basedao.java

package cn.jbit.leavereccords.dao;

import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;

import cn.jbit.leavereccords.util.databaseutil;

/**
 * 执行数据库操作的工具类。
 */
public class basedao {

    private connection conn;

    /**
     * 增、删、改操作的方法
     * 
     * @param sql   sql语句
     * @param prams 参数数组
     * @return 执行结果
     * @throws sqlexception
     */
    protected int executeupdate(string sql, object... params) throws sqlexception {
        int result = 0;
        conn = databaseutil.getconnection();
        preparedstatement pstmt = null;
        try {
            pstmt = conn.preparestatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setobject(i + 1, params[i]);
            }
            result = pstmt.executeupdate();
        } catch (sqlexception e) {
            e.printstacktrace();
            throw e;
        } finally {
            databaseutil.closeall(null, pstmt, null);
        }
        return result;
    }

    /**
     * 查询操作的方法
     * 
     * @param sql    sql语句
     * @param params 参数数组
     * @return 查询结果集
     * @throws sqlexception
     */
    protected resultset executequery(string sql, object... params) throws sqlexception {
        preparedstatement pstmt = null;
        conn = databaseutil.getconnection();
        resultset rs = null;
        try {
            pstmt = conn.preparestatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setobject(i + 1, params[i]);
            }
            rs = pstmt.executequery();
        } catch (sqlexception e) {
            e.printstacktrace();
            throw e;
        }
        return rs;
    }
}

leaverecords.java

package cn.jbit.leavereccords.entity;

import java.util.date;

public class leaverecords {
    private integer id;// 编号
    private string name;// 请假人姓名
    private date leavetime;// 请假时间
    private string reason;// 请假原因

    public leaverecords() {
        super();
    }

    public leaverecords(string name, date leavetime, string reason) {
        super();
        this.name = name;
        this.leavetime = leavetime;
        this.reason = reason;
    }

    public leaverecords(integer id, string name, date leavetime, string reason) {
        super();
        this.id = id;
        this.name = name;
        this.leavetime = leavetime;
        this.reason = reason;
    }

    //省略了getter和setter方法

}

leaverecordsservice.java

package cn.jbit.leavereccords.service;

import java.util.list;
import java.util.map;

import cn.jbit.leavereccords.entity.leaverecords;
import cn.jbit.leavereccords.util.page;

public interface leaverecordsservice {
    /**
     * 分页
     * @param page
     */
    public void recordslist(page<leaverecords> page);
    /**
     * 添加请假信息
     * 
     * @param leaverecords
     * @return
     */
    public integer insertleaverecords(leaverecords leaverecords);

    /**
     * 删除请假信息
     * 
     * @param id
     * @return
     */
    public integer deleteleaverecords(int id);

}

leaverecordsserviceimpl.java

package cn.jbit.leavereccords.service.impl;

import java.util.list;
import java.util.map;

import cn.jbit.leavereccords.dao.leaverecordsdao;
import cn.jbit.leavereccords.dao.impl.leaverecordsdaoimpl;
import cn.jbit.leavereccords.entity.leaverecords;
import cn.jbit.leavereccords.service.leaverecordsservice;
import cn.jbit.leavereccords.util.page;

public class leaverecordsserviceimpl implements leaverecordsservice {
    leaverecordsdao leaverecordsdao = new leaverecordsdaoimpl();

    @override
    public integer insertleaverecords(leaverecords leaverecords) {
        return leaverecordsdao.addleaverecords(leaverecords);
    }

    @override
    public integer deleteleaverecords(int id) {
        return leaverecordsdao.deleteleaverecords(id);
    }

    @override
    public void recordslist(page<leaverecords> page) {
        int count=leaverecordsdao.count();//获取所有消息的数量
        page.settotalcount(count);
        //判断传入的页面是否合法
        if(page.getpageindex()>page.gettotalpagecount()) {
            //确保页面不会超过总页数
            page.setpageindex(page.gettotalpagecount());
        }
        list<leaverecords> datalist=leaverecordsdao.selecteleaverecords(page.getpageindex(), page.getpagesize());
        page.setdatalist(datalist);
    }
}

leaverecordsdaotest.java

package cn.jbit.leavereccords.test;

import java.text.parseexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import org.junit.test;

import cn.jbit.leavereccords.dao.leaverecordsdao;
import cn.jbit.leavereccords.dao.impl.leaverecordsdaoimpl;
import cn.jbit.leavereccords.entity.leaverecords;
import cn.jbit.leavereccords.service.leaverecordsservice;
import cn.jbit.leavereccords.service.impl.leaverecordsserviceimpl;

public class leaverecordsdaotest {
    @test
    public void leaverecords() {
        leaverecordsservice recordsservice=new leaverecordsserviceimpl();
        //添加
        string date="2018-08-07";
        simpledateformat sdf=new simpledateformat("yyyy-mm-dd");
        date leavetime=null;
        try {
            leavetime=(date)sdf.parse(date);
        } catch (parseexception e) {
            e.printstacktrace();
        }
        leaverecords leaverecords=new leaverecords("www", leavetime, "successful");
        int result=recordsservice.insertleaverecords(leaverecords);
        system.out.println(result);
        
        //删除
        int num=recordsservice.deleteleaverecords(20);
        system.out.println(num);
        //分页查询
        leaverecordsdao recordsdao=new leaverecordsdaoimpl();
        list<leaverecords> list=recordsdao.selecteleaverecords(1, 5);
        for (leaverecords leaverecords2 : list) {
            system.out.println(leaverecords2.getname());
        }
        
        //查询
        map<string , object> param=new hashmap<string, object>();
        param.put("records", new leaverecords(null, null, null, null));
        list<leaverecords> listinfo=recordsservice.findleaverecords(param);
        for (leaverecords leaverecords2 : listinfo) {
            system.out.println(leaverecords2.getleavetime());
        }
    }
}

leaverecordsservlet.java

package cn.jbit.leavereccords.servlet;

import java.io.ioexception;
import java.io.printwriter;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.list;

import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import cn.jbit.leavereccords.entity.leaverecords;
import cn.jbit.leavereccords.service.leaverecordsservice;
import cn.jbit.leavereccords.service.impl.leaverecordsserviceimpl;
import cn.jbit.leavereccords.util.page;

@webservlet(urlpatterns = { "/leaverecordsservlet" }, name = "leaverecordsservlet")
public class leaverecordsservlet extends httpservlet {

    private static final long serialversionuid = -8076807217250462175l;

    @override
    protected void doget(httpservletrequest request, httpservletresponse response)
            throws servletexception, ioexception {
        dopost(request, response);
    }

    @override
    protected void dopost(httpservletrequest request, httpservletresponse response)
            throws servletexception, ioexception {
        request.setcharacterencoding("utf-8");
        response.setcontenttype("text/html;charset=utf-8");
        leaverecordsservice leaverecordsservice = new leaverecordsserviceimpl();
        // 根据action决定作什么操作
        string action = request.getparameter("action");
        //分页查询
        if ("list".equals(action)) {
            // 获取当前页数参数
            string pageindex = request.getparameter("pageindex");
            // 获取页面大小参数(每页显示的数量)
            // string pagesize = request.getparameter("pagesize");
            int index = 1;// 设置首页为1
            int size = 8;// 设置页面大小为8条数据
            try {
                if (pageindex == null) {
                    index = 1;
                } else {
                    index = integer.parseint(pageindex);
                }

                // size=integer.parseint(pagesize);
            } catch (exception e) {
                e.printstacktrace();
            }

            // 将分页参数封装到分页对象中
            page<leaverecords> page = new page<leaverecords>();
            page.setpageindex(index);
            page.setpagesize(size);

            // 调用service层进行分页查询
            leaverecordsservice.recordslist(page);

            // 尾页填充空白行(为了视觉美观)(效果图如下图中的空白行)
            list<leaverecords> recordslist = page.getdatalist();
            if (recordslist.size() < page.getpagesize()) {
                for (int i = recordslist.size(); i < page.getpagesize(); i++)
                    recordslist.add(null);
            }
            page.setdatalist(recordslist);
            
            // 将业务层处理后的分页对象存放至request作用域中
            request.setattribute("page", page);
            request.getrequestdispatcher("select.jsp").forward(request, response);
        }
        //删除记录
        if ("delete".equals(action)) {
            string sid = request.getparameter("opt");
            int id = integer.parseint(sid);
            int deleteinfo = leaverecordsservice.deleteleaverecords(id);
            printwriter out = response.getwriter();
            boolean result;
            if (deleteinfo > 0) {
                result = true;
            } else {
                result = false;
            }
            out.print(result);
            out.flush();
            out.close();
        }
        //增加记录
        if("insert".equals(action)) {
            //请假人姓名
            string name=request.getparameter("name");
            //请假时间
            string time=request.getparameter("leavetime");
            simpledateformat sdf=new simpledateformat("yyyy-mm-dd");
            date leavetime=null;
            try {
                leavetime = (date)sdf.parse(time);
            } catch (parseexception e) {
                e.printstacktrace();
            }
            //请假原因
            string reason=request.getparameter("reason");
            leaverecords leaverecords=new leaverecords(name, leavetime, reason);
            int result= leaverecordsservice.insertleaverecords(leaverecords);
            printwriter out=response.getwriter();
            if(result>0) {
                out.println("<script type='text/javascript'>" 
                        + "alert('添加成功!');" 
                        + "location.href='leaverecordsservlet?action=list'"
                        + "</script>");
            } else {
                out.print("<script type='text/javascript'>" 
                        + "alert('添加失败!')" 
                        + "loction='leaverecordsservlet?action=insert'" + "</script>");
            }
        }
    }
}

          MySQL+Service+Servlet+Jsp实现Table表格分页展示数据

configmanager.java

package cn.jbit.leavereccords.util;

import java.io.ioexception;
import java.io.inputstream;
import java.util.properties;

/**
 * 数据库参数配置文件查找工具类
 * @author 逆風〠飛�?
 *
 */
public class configmanager {
    private static properties props = null;

    static {
        inputstream is = null;
        is = configmanager.class.getclassloader().getresourceasstream("database.properties");
        if (is == null)
            throw new runtimeexception("找不到数据库参数配置文件�?");
        props = new properties();
        try {
            props.load(is);
        } catch (ioexception e) {
            throw new runtimeexception("数据库配置参数加载错误!", e);
        } finally {
            try {
                is.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }

    public static string getproperty(string key) {
        return props.getproperty(key);
    }
}

databaseutil.java

package cn.jbit.leavereccords.util;

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;

/**
 * 数据库连接与关闭工具类�??
 * 
 */
public class databaseutil {
    private static string driver = configmanager.getproperty("driver");// 数据库驱动字符串
    private static string url = configmanager.getproperty("url"); // 连接url字符�?
    private static string user = configmanager.getproperty("user"); // 数据库用户名
    private static string password = configmanager.getproperty("password"); // 用户密码

    static {
        try {
            class.forname(driver);
        } catch (classnotfoundexception e) {
            e.printstacktrace();
        }
    }

    /**
     * 获取数据库连接对象�??
     */
    public static connection getconnection() throws sqlexception {
        // 获取连接并捕获异�?
        connection conn = null;
        try {
            conn = drivermanager.getconnection(url, user, password);
        } catch (sqlexception e) {
            e.printstacktrace();
            throw e;
        }
        return conn;// 返回连接对象
    }

    /**
     * 
     * 关闭数据库连�?
     * @param conn 数据库连�?
     * @param stmt statement对象
     * @param rs   结果�?
     */
    public static void closeall(connection conn, statement stmt, resultset rs) {
        // 若结果集对象不为空,则关�?
        try {
            if (rs != null && !rs.isclosed())
                rs.close();
        } catch (exception e) {
            e.printstacktrace();
        }
        // 若statement对象不为空,则关�?
        try {
            if (stmt != null && !stmt.isclosed())
                stmt.close();
        } catch (exception e) {
            e.printstacktrace();
        }
        // 若数据库连接对象不为空,则关�?
        try {
            if (conn != null && !conn.isclosed())
                conn.close();
        } catch (exception e) {
            e.printstacktrace();
        }
    }

}

emptyutils.java

package cn.jbit.leavereccords.util;

import java.util.collection;
import java.util.map;

/**
 * 判断是否为空的工具类
 * @author 逆風〠飛翔
 *
 */
public class emptyutils {
    // 鍒ょ┖
    public static boolean isempty(object obj) {
        if (obj == null)
            return true;
        if (obj instanceof charsequence)
            return ((charsequence) obj).length() == 0;
        if (obj instanceof collection)
            return ((collection) obj).isempty();
        if (obj instanceof map)
            return ((map) obj).isempty();
        if (obj instanceof object[]) {
            object[] object = (object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isempty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    public static boolean isnotempty(object obj) {
        return !isempty(obj);
    }

    private boolean validpropertyempty(object... args) {
        for (int i = 0; i < args.length; i++) {
            if (emptyutils.isempty(args[i])) {
                return true;
            }
        }
        return false;
    }
}

page.java

package cn.jbit.leavereccords.util;

import java.util.list;

/**
 * 分页用的基类,抽取了通用的分页参数
 *
 */
public class page<t> {
    private int pageindex=1;// 当前页数
    private int pagesize=8 ;// 每页显示的行数
    private int totalcount;// 总记录数
    private int totalpagecount;// 总页数
    private list<t> datalist ;// 分页结果的泛型集合

    public int getpageindex() {
        return pageindex;
    }

    public void setpageindex(int pageindex) {
        // 判断当前页码,如果页码大于零,则显示为当前的pageindex页面,否则pageindex为1,即第一页
        if (pageindex > 0) {
            this.pageindex = pageindex;
        } else {
            this.pageindex = 1;
        }
    }

    public int getpagesize() {
        return pagesize;
    }

    public void setpagesize(int pagesize) {
        // 设置每页显示数据的条数
        if (pagesize > 0) {
            this.pagesize = pagesize;
        } else {
            this.pagesize = 5;
        }
    }

    public int gettotalcount() {
        return totalcount;
    }

    public void settotalcount(int totalcount) {
        if (totalcount > 0) {
            //总记录数
            this.totalcount = totalcount;
            //计算总页数
            this.totalpagecount = (this.totalcount % this.pagesize == 0) ? (this.totalcount / this.pagesize)
                    : (this.totalcount / this.pagesize + 1);
        }
    }

    public int gettotalpagecount() {
        return totalpagecount;
    }

    public void settotalpagecount(int totalpagecount) {
        this.totalpagecount = totalpagecount;
    }

    public list<t> getdatalist() {
        return datalist;
    }

    public void setdatalist(list<t> datalist) {
        this.datalist = datalist;
    }
}

配置文件代码:

database.properties

#数据库连接驱动
driver=com.mysql.jdbc.driver
#数据库用户名
user=webtest
#数据库密码
password=1234
#连接url字符串
url=jdbc\:mysql\://localhost\:3306/leaverecords?usessl\=false

jsp页面代码:

查询jsp:select.jsp

<%@page import="cn.jbit.leavereccords.entity.leaverecords"%>
<%@page import="cn.jbit.leavereccords.util.page"%>
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" 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>
<%
    page recordspage = (page) request.getattribute("page");
    //只要是访问select.jsp都需要先访问leaverecordsservlet?action=list让作用域中有msgpage的数据
    if (recordspage == null) {
        request.getrequestdispatcher("leaverecordsservlet?action=list").forward(request, response);
        return;
    }
    
    string[] leaverecordsinfo = { "编号", "姓名", "请假时间", "请假原因", "操作" };
    request.setattribute("leaverecordsinfo", leaverecordsinfo);
%>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/delete.js"></script>
<body>
    <div align="center" style="margin-top: 130px;">
        <h1 style="font-weight: bold;">请假记录列表</h1>
        <div align="left" style="width: 790px"><a  href="insert.jsp">添加请假记录</a></div>
        <form action="leaverecordsservlet?action=list" method="post" id="form" name="form1">
            <table border="1" width="800px" style="text-align: center;">
                <thead style="background-color: #999999">
                    <c:foreach var="leaverecordsinfo"
                        items="${requestscope.leaverecordsinfo}">
                        <th>${leaverecordsinfo}</th>
                    </c:foreach>
                </thead>
                <tbody>
                    <c:foreach var="leaverecordslist"
                        items="${requestscope.page.datalist}" varstatus="status">
                        <tr height="30px"
                            <c:if test="${status.index % 2 ==1}">style="background-color:#9cd1f3;"</c:if>>
                            <td>${leaverecordslist.id}</td>
                            <td>${leaverecordslist.name}</td>
                            <td>${leaverecordslist.leavetime}</td>
                            <td>${leaverecordslist.reason}</td>
                            <td>
                               <c:if test="${leaverecordslist!=null}">
                                  <a href="javascript:void(0)" onclick="del(${leaverecordslist.id})">删除 </a>
                               </c:if>
                            </td>
                        </tr>
                    </c:foreach>
                </tbody>
            </table>
        </form>
        <div style="width: 800px;background-color: #9cd1f3;line-height: 40px;">
            <a href="leaverecordsservlet?action=list&pageindex=1">首页</a> &#160;&#160;
            <a href="leaverecordsservlet?action=list&pageindex=${page.pageindex-1<1?1:page.pageindex-1 }">上一页</a>&#160;&#160;
              &#160;&#160;&#160;第${page.pageindex }页/共${page.totalpagecount }页 &#160;&#160;&#160;
            <a href="leaverecordsservlet?action=list&pageindex=${page.pageindex+1>page.totalpagecount?page.pageindex:page.pageindex+1 }">下一页</a>&#160;&#160;
            <a href="leaverecordsservlet?action=list&pageindex=${page.totalpagecount }">末页</a>    
             <div style="float: right; ">
                         
             当前页<select id="select" onchange="document.all.form1.submit();">
                <c:foreach begin="1" end="${page.totalpagecount}" var="pagenum">
                  <option value="${pagenum}" ${page.pageindex==pagenum?'selected="selected"':''}>${pagenum}</option>
               </c:foreach>
              </select>.
                 共${page.totalcount}条. 每页显示${page.pagesize}条&#160;&#160;&#160;&#160;
               </div>
        </div>
    </div>
</body>
</html>

删除的js:delete.js

function del(id) {
    var dele = confirm("确定要删除吗?");
    if (dele == true) {
        $.ajax({
            "url" : "leaverecordsservlet?action=delete",
            "type" : "post",
            "data" : "opt=" + id,
            "datatype" : "text",
            "success" : success,
            "error" : error,
        });

        // 删除成功回调函数
        function success(data) {
            if (data == "true") {
                alert("删除成功!");
                location.href="leaverecordsservlet?action=list";
            } else {
                alert("删除失败!");
            }
        }
        // 请求失败回调函数
        function error(date) {
            alert("请求失败!");
        }
    }
}

添加jsp:insert.jsp

<%@ 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>my jsp 'insert.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>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/insert.js"></script>
<body>
    <div align="center" style="margin-top: 130px">
    <h2>添加请假记录</h2>
        <form action="leaverecordsservlet?action=insert" method="post"
            onsubmit="return check()">
            <table style="padding-bottom: 30px">
                <tr>
                    <td>姓名:</td>
                    <td><input type="text" name="name" id="name" />
                </tr>
                <tr>
                    <td>请假时间:</td>
                    <td><input type="text" name="leavetime" id="leavetime" />
                    <div style="display: inline;">格式要求:yyyy-mm-dd</div>
                </tr>
                <tr>
                    <td>请假原因:</td>
                    <td><textarea rows="5" cols="50" name="reason" id="reason"></textarea>
                    </td>
                </tr>
            </table>
            <input type="submit" value="提交" />&#160;&#160;<input type="reset" value="重置" />
        </form>
    </div>
</body>
</html>

添加的非空验证的js:insert.js

//非空验证
function check() {
    var name = $("#name").val();
    var leavetime = $("#leavetime").val();
    var context=$("context").val();
    var reg = /^([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))$/;
    if (name == "" || leavetime=="" || context=="" ) {
        alert("信息未填写完整,请完善!");
        return false;
    }
    if(reg.test(leavetime)==false){
        alert("日期格式有误,请重新填写!");
        return false;
    }
}