- 先来看一看分页的实现原理
首先,新建Java Web项目
一. 梳理业务逻辑
重定向到URL(跳转到StudentViewAction页面)//index.jsp页面
1.从页面接收可变的值
2.接收值有问题时,初始化为1
3.如果没有问题,把String类型接收值强转成Integer
4.实例DAO方法,调用findStudentListByPageCount()方法(该方法得到总条数)
5.计算总页数:总页数 = 总条数 % 页容量
6.判断接收到页面传来的值是否小于1页
7.调用DAO中findStudentListByPageCount()(该方法获取数据集合)
8.封装打包页面
9.转发页面
request.getRequestDispatcher("list.jsp").forward(request, response);
//request.getRequestDispatcher("list.jsp") 找到要转发的页面
//forward(request, response); 实现转发
二. 实现界面展示
1.封装工具类JDBCUtil.java文件, 作用是连接数据库
package com.fyl.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
/**
* 文档注释(Java连接数据库的工具类)
*
*/
public class JDBCUtil {
// 注意:四个属性:驱动, 地址(URL), 用户名, 密码
// 驱动类:通过一个类名告诉java我现在使用的是什么数据库
private static final String CONN_DRIVER = "com.mysql.jdbc.Driver";
// URL:告诉Java我的数据库的具体位置(网络标识:通过什么端口哪台电脑获取什么资源)
private static final String CONN_URL = "jdbc:mysql://127.0.0.1:3306/student_db?characterEncoding=UTF-8";
// 用户名
private static final String CONN_USER_NAME = "root";
// 密码
private static final String CONN_USER_PASS = "123456";
public static Connection getConn() {
// 创建方法的返回变量
Connection conn = null;
try {
// 1.加载驱动类 让Java知道我们创建什么数据库的实例
Class.forName(CONN_DRIVER);
// 通过已经加载好的驱动类给我们提供连接
conn = DriverManager.getConnection(CONN_URL, CONN_USER_NAME,
CONN_USER_PASS);
} catch (ClassNotFoundException e) {
System.out.println("add DriverManager error!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQL error!");
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet set, PreparedStatement ps,
Connection conn) {
try {
if (null != set) {
set.close();
}
if (null != ps) {
ps.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
System.out.println("closeAll ERROR!");
e.printStackTrace();
}
}
public static void main(String[] args) {
// 获取数据库连接
Connection conn = JDBCUtil.getConn();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("请素输入要查看的数据:");
int i = scan.nextInt();
int start = (i - 1) * 10;
int size = 10;
// 2.编写SQL语句(查询id > 0的数据, 连续查询10条记录)
String sql = "SELECT * FROM student WHERE s_id LIMIT ?,?";
// SELECT * FROM student WHERE s_id > 10 AND s_id <= (10 + 10)
// 3.运行SQL语句
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, start);
ps.setInt(2, size);
// 4.执行后返回结果(execute执行Query结果)
ResultSet set = ps.executeQuery();
System.out.println("学生编号\t学生姓名\t学生年龄\t入学时间\t学费");
for (; set.next();) {
System.out.print(set.getInt("S_ID") + "\t");
System.out.print(set.getString("S_NAME") + "\t");
System.out.print(set.getInt("S_AGE") + "\t");
System.out.print(set.getDate("S_INTODATE") + "\t");
System.out.print(set.getDouble("S_MONEY") + "\t");
System.out.println();
}
} catch (SQLException e) {
System.out.println("select error");
e.printStackTrace();
}
}
}
}
2.创建数据库实体类Student.java文件(Model层)
package com.fyl.entity;
import java.io.Serializable;
import java.util.Date;
/**
* 实体类
* @author Administrator
*
*/
public class Student implements Serializable {
private static final long serialVersionUID = 1L;//添加唯一标识
private Integer id;
private String name;
private int age;
private Date date;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
3.index.jsp界面(呈现给用户的第一个界面)
<head>
<title>系统首页</title>
</head>
<body>
<%
// 重定向到URL
request.getRequestDispatcher("StudentViewAction").forward(request, response);
%>
</body>
4.新建servlet文件StudentViewAction.java(Controller层)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//封装数据给页面
//整理页面需要的数据
int pageIndex = 0;//页面 //页面每次请求传过来的
int pageSize = 10;//
int totalCount = 0;
int totalPge = 0;
List<Student> list = null;
//从页面接收可变的值
String pi = request.getParameter("pageIndex");
//pi有问题的时候,初始化为1
if (null == pi || "".equals(pi)) {
pi = "1";
}
//如果pi没有问题的时候
pageIndex = Integer.parseInt(pi);
//从数据接收值
StudentDAO dao = new StudentDAOImpl();
//调用DAO方法
totalCount = dao.findStudentListByPageCount();
//计算总页数
totalPge = totalCount % pageSize == 0?totalCount/pageSize:totalCount/pageSize + 1;
//判断pageIndex的边界值
if (pageIndex < 1) {
pageIndex = 1;
}
if (pageIndex > totalPge) {
pageIndex = totalPge;
}
//获取数据集合
list = dao.findStudentListByPage(pageIndex, pageSize);
//封装打包页面
request.setAttribute("pageIndex", pageIndex);
request.setAttribute("pageSize", pageSize);
request.setAttribute("totalCount", totalCount);
request.setAttribute("totalPge", totalPge);
request.setAttribute("list", list);
//转发页面
request.getRequestDispatcher("list.jsp").forward(request, response);
}
}
新建list.jsp界面接收StudentViewAction传来的值
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>数据展示</title>
<script type="text/javascript">
function goUpdate(id){
window.location.href = "StudentFindByIDViewAction?id=" + id;
}
function goDelete(id){
var con = window.confirm("您确定删除ID为" + id + "这条数据吗?" );
if(con){
//删除
window.location.href = "StudentDeleteAction?id=" + id;
}
}
function goPage(pageIndex){
window.location.href = "StudentViewAction?pageIndex="+pageIndex;
}
function goPage(pageIndex){
window.location.href = "StudentViewAction?pageIndex="+pageIndex;
}
function goAdd(){
window.location.href = "add.jsp";
}
</script>
</head>
<body>
<input type="button" value="添加新学生" onclick="goAdd();" />
<table border="1">
<tr>
<th colspan="6">
一共查询出${totalCount}条数据,每页展示${pageSize}条,一共有${totalPage}页,当前浏览的是第${pageIndex}页
</th>
</tr>
<tr>
<th>学生ID</th>
<th>学生姓名</th>
<th>学生年龄</th>
<th>入学时间</th>
<th>学费</th>
<th>操作</th>
</tr>
<c:forEach items="${list}" var="s">
<tr align="center">
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.age}</td>
<td><fmt:formatDate pattern="yyyy年MM月dd日" value="${s.date}" /></td>
<td>
<fmt:formatNumber type="currency" value="${s.money}" />
</td>
<td>
<input type="button" value="更新" onclick="goUpdate(${s.id});" /> ||
<input type="button" value="删除" onclick="goDelete(${s.id});" />
</td>
</tr>
</c:forEach>
<tr>
<th colspan="6">
<input type="button" value="首页" onclick="goPage(1);"/>
<c:choose>
<c:when test="${pageIndex <= 1}">
<input type="button" value="上一页" disabled="disabled" />
</c:when>
<c:otherwise>
<input type="button" value="上一页" onclick="goPage(${pageIndex-1});"/>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${pageIndex >= totalPage}">
<input type="button" value="下一页" disabled="disabled" />
</c:when>
<c:otherwise>
<input type="button" value="下一页" onclick="goPage(${pageIndex+1});"/>
</c:otherwise>
</c:choose>
<input type="button" value="末页" onclick="goPage(${totalPge});"/>
</th>
</tr>
</table>
</body>
</html>
三. 实现增删查改
- 创建接口, 新建StudentDAO.java接口文件, 添加增删查改方法
package com.fyl.dao;
import java.util.List;
import com.fyl.entity.Student;
public interface StudentDAO {
/**
* 更据id删除
* @param id
* @return
* @throws RuntimeException
*/
public boolean deleteStudent(Integer id) throws RuntimeException;
/**
* 根据ID查询单个学生对象
* @param id
* @return
* @throws RuntimeException
*/
public Student findStudentByID(Integer id) throws RuntimeException;
/*
* 添加学生方法
* @param student 要添加的学生
* @return 添加成功返回true 添加失败返回false
* @throws RuntimeException
*/
public boolean insertStudent(Student student)throws RuntimeException;
/**
* 查询数据库的总条数
* @return 总条数
* @throws RuntimeException
*/
public int findStudentListByPageCount() throws RuntimeException;
/**
* 获取分页数集合
* @param pageIndex 页码
* @param pageSize 页容量
* @return 已经分页的list集合
* @throws RuntimeException
*/
public List<Student> findStudentListByPage(Integer pageIndex, Integer pageSize) throws RuntimeException;
/*
* 更新学生信息
* @param student
* @return
* @throws RuntimeException
*/
public boolean updateStudent(Student student) throws RuntimeException;
}
2.新建StudentDAOImpl.java文件,实现接口
package com.fyl.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.fyl.dao.StudentDAO;
import com.fyl.entity.Student;
import com.fyl.util.JDBCUtil;
public class StudentDAOImpl implements StudentDAO {
// TODO
public int findStudentListByPageCount() throws RuntimeException {
// 1.创建方法的返回变量
int totalCount = 0;
// 3.获取数据库连接
Connection conn = JDBCUtil.getConn();
// 4.编写SQL语句
String sql = "SELECT COUNT(S_ID) FROM STUDENT";
// 执行SQL语句
PreparedStatement ps = null;
ResultSet set = null;
try {
ps = conn.prepareStatement(sql);
set = ps.executeQuery();
//处理
if (set.next()) {
totalCount = set.getInt(1);
}
} catch (SQLException e) {
// TODO
e.printStackTrace();
} finally {
JDBCUtil.closeAll(set, ps, conn);
}
return totalCount;
}
// TODO
public List<Student> findStudentListByPage(Integer pageIndex,
Integer pageSize) throws RuntimeException {
List<Student> list = new ArrayList<Student>();
//2.1获取数据库连接
Connection conn = JDBCUtil.getConn();
//3. 创建SQL语句
String sql = "SELECT * FROM STUDENT WHERE S_ID LIMIT ?,?";
//4.执行SQL语句
PreparedStatement ps = null;
ResultSet set = null;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, (pageIndex-1) * pageSize);
ps.setInt(2, pageSize);
set = ps.executeQuery();
Student s = null;
while (set.next()) {
s = new Student();
//封装数据
s.setId(set.getInt("S_ID"));
s.setName(set.getString("S_NAME"));
s.setAge(set.getInt("S_AGE"));
s.setMoney(set.getDouble("S_MONEY"));
s.setDate(set.getDate("S_INTODATE"));
// 将封装好的Student对像装入集合
list.add(s);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeAll(set, ps, conn);
}
return list;
}
public boolean insertStudent(Student student) throws RuntimeException {
// TODO Auto-generated method stub
//1.定义方法返回变量
boolean con = false;
//3. 获取数据库连接
Connection conn = JDBCUtil.getConn();
//4. 编写SQL语句
String sql = "INSERT INTO STUDENT (S_NAME,S_AGE,S_INTODATE,S_MONEY) VALUES (?,?,?,?)";
// 5. 执行SQL语句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
// 6. 是否有占位符赋值?
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setDate(3, new java.sql.Date(student.getDate().getTime()));
ps.setDouble(4, student.getMoney());
int count = ps.executeUpdate(); // 执行增 删 改 SQL 返回int类型的受影响行数
// 7. 改变方法的返回值
con = count>0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 2. 返回con
return con;
}
// TODO 根据id查询
public Student findStudentByID(Integer id) throws RuntimeException {
//创建方法的返回值
Student student = null;
Connection conn = JDBCUtil.getConn();
//编写SQL语句
String sql = "SELECT * FROM STUDENT WHERE S_ID = ?";
//执行SQL语句
PreparedStatement ps = null;
ResultSet set = null;
try {
ps = conn.prepareStatement(sql);
//是否有占位符
ps.setInt(1, id);
set = ps.executeQuery();
if(set.next()){
//创建实例对象封装查询数据
student = new Student();
student.setId(set.getInt("S_ID"));
student.setAge(set.getInt("S_AGE"));
student.setDate(set.getDate("S_INTODATE"));
student.setMoney(set.getDouble("S_MONEY"));
student.setName(set.getString("S_NAME"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.closeAll(set, ps, conn);
}
return student;
}
// TODO 更新学生信息
public boolean updateStudent(Student student) throws RuntimeException {
//创建方法的返回值
boolean con = false;
//获取数据库连接
Connection conn = JDBCUtil.getConn();
//编写SQL语句
String sql = "UPDATE STUDENT SET S_NAME=?,S_AGE=?,S_INTODATE=?,S_MONEY=? WHERE S_ID=?";
//执行SQL语句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
//是否有占位符
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setDate(3, new java.sql.Date(student.getDate().getTime()));
ps.setDouble(4, student.getMoney());
ps.setInt(5, student.getId());
int count = ps.executeUpdate();
con = count>0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
// TODO delete
public boolean deleteStudent(Integer id) throws RuntimeException {
//创建方法的返回变量
boolean con = false;
//获取数据库链接
Connection conn = JDBCUtil.getConn();
//编写SQL语句
String sql = "DELETE FROM STUDENT WHERE S_ID = ?";
//执行SQL语句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
int count = ps.executeUpdate();
con = count > 0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.closeAll(null, ps, conn);
}
return con;
}
// TODO main
public static void main(String[] args) {
StudentDAO dao = new StudentDAOImpl();
System.out.println(dao.findStudentListByPageCount());
}
}
3.创建servlet文件StudentAddAction.java接收用户传入的值,添加到数据库并展示到list.jsp(增)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentAddAction extends HttpServlet {
private static final long serialVersionUID = 1L;
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");
//1. 接收页面数据
String studentName = request.getParameter("studentName");
String studentAge = request.getParameter("studentAge");
String intoDate = request.getParameter("intoDate");
String money = request.getParameter("money");
//2. 封装
Student student = new Student();
student.setName(studentName);
student.setAge(Integer.parseInt(studentAge));
student.setMoney(Double.parseDouble(money));
// String 转 时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = df.parse(intoDate);
student.setDate(d);
} catch (ParseException e) {
e.printStackTrace();
}
// 3. 创建DAO层对象添加到数据库
StudentDAO dao = new StudentDAOImpl();
boolean con = dao.insertStudent(student);
if(con){
// 添加成功
response.sendRedirect("StudentViewAction");
}else{
// 添加失败
// 通过服务器的响应流主动向客户端发送信息
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String msg = "<script type=\"text/javascript\">alert(\"添加失败\");history.back();</script>";
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
}
}
}
4.创建servlet文件StudentDeleteAction.java接收用户传入的值,删除数据库中指定文件并展示到list.jsp(删)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
public class StudentDeleteAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1. 确定编码
request.setCharacterEncoding("UTF-8");
//2. 获取页面数据
String id = request.getParameter("id");
//3. 创建DAO方法执行删除
StudentDAO dao = new StudentDAOImpl();
boolean con = dao.deleteStudent(Integer.parseInt(id));
if(con){
//添加成功
response.sendRedirect("StudentViewAction");
}else{
//添加失败
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String msg = "<script type=\"text/javascript\">alert(\"添加失败\");history.back();</script>";
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
}
}
}
- 创建servlet文件StudentFindByIDViewAction.java接收用户传入的值,查询数据库中指定文件并展示到list.jsp(查)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentFindByIDViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
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");
//接收页面输入
String id = request.getParameter("id");
//创建DAO层对象
StudentDAO dao = new StudentDAOImpl();
Student student = dao.findStudentByID(new Integer(id));
request.setAttribute("stu", student);
request.getRequestDispatcher("update.jsp").forward(request, response);
}
}
6.创建servlet文件StudentUpdateAction.java接收用户传入的值,更新数据库中指定文件并展示到list.jsp(改)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentUpdateAction extends HttpServlet {
private static final long serialVersionUID = 1L;
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");
//1. 设置接收页面数据
String studentId = request.getParameter("studentId");
String studentName = request.getParameter("studentName");
String studentAge = request.getParameter("studentAge");
String intoDate = request.getParameter("Date");
String money = request.getParameter("money");
//2. 封装
Student student = new Student();
String studentId1 = studentId.trim();
student.setId(Integer.parseInt(studentId1));
student.setName(studentName);
student.setAge(Integer.parseInt(studentAge));
student.setMoney(Double.parseDouble(money));
//String转时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = df.parse(intoDate);
student.setDate(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3. 创建DAO层对象添加到数据库
StudentDAO dao = new StudentDAOImpl();
boolean con = dao.updateStudent(student);
if(con)0.{
//添加成功
response.sendRedirect("StudentViewAction");
}else{
//添加失败
//通过服务器的响应流主动向客户端发送信息
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String msg = "<script type=\"text/javascript\">alert(\"添加失败\");history.back();</script>";
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
}
}
}