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

下面以一个示例讲解如何使用MySQL+Service+Servlet+Jsp实现Table表格分页展示数据:

eg:请假管理系统

要求如下:

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

                    

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

                        

      

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

              

        

  

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

                

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

              

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

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

             

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

 二、MySQL数据库设计如下:

    

三、项目分层设计如下:

                  

项目代码如下:

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

          

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

 

posted @ 2018-10-25 09:42  纪元A梦  Views(3943)  Comments(0Edit  收藏  举报