个人理解:
1、一个页面是一个对象,有一些属性(总页数、当前页、每页记录数、总记录数、每页显示的记录 即记录集(Commodity))
2、Commodity也是一个对象,只不过这个对象是页面的属性而已,Commodity也有一些属性(价格、名称、评价等)
3、通过数据库查询得到Commodity这个对象的属性的值,然后将Commodity对象,作为属性值,放到页面的记录集属性里面去
4、然后将页面的值传到前端,显示出来
- 首先要创建两个实体类,我放在pojo包里面了:
Commodity.class(定义商品的一些属性)
PageBean.class(定义页面的一些属性)
package com.gk.pojo;
public class Commodity {
private int id;//商品id
private String name;//商品名
private String brand;//商品品牌
private String state;//对商品的描述
private double praise;//价格
private int sell;//售价
private double grade;//商品评分
public Commodity(int id, String name, String brand, String state, double praise, int sell, double grade) {
//商品有参构造方法,便于数据库查询时进行直接赋值,就不需要使用setter方法了
this.id = id;
this.name = name;
this.brand = brand;
this.state = state;
this.praise = praise;
this.sell = sell;
this.grade = grade;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public double getPraise() {
return praise;
}
public void setPraise(double praise) {
this.praise = praise;
}
public int getSell() {
return sell;
}
public void setSell(int sell) {
this.sell = sell;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Commodity{" +
"id=" + id +
", name='" + name + '\'' +
", brand='" + brand + '\'' +
", state='" + state + '\'' +
", praise=" + praise +
", sell=" + sell +
", grade=" + grade +
'}';
}
}
package com.gk.pojo;
import java.util.List;
public class PageBean<T> {
private int pageSize = 5;//每页显示的条数
private int totalPage;//总页数
private int totalRecord;//总记录数
private int currentPage;//当前页数
private List<T> list;//记录集
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
//在这里就可以直接计算总页数是多少
this.totalRecord = totalRecord;
//如果总记录数刚好可以整除一页的记录数,那总页数就是得出的结果
//否则将+1
if((this.totalRecord%this.pageSize) == 0){
this.totalPage = this.totalRecord/this.pageSize;
}else{
this.totalPage = this.totalRecord/this.pageSize + 1;
}
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
@Override
public String toString() {
return "PageBean{" +
"pageSize=" + pageSize +
", totalPage=" + totalPage +
", totalRecord=" + totalRecord +
", currentPage=" + currentPage +
", list=" + list +
'}';
}
}
- 数据库查询结果
定义两个类(我都放在dao包里面)
1、DaoConnect.class(进行数据库连接)
2、FindShop.class (进行数据库查询)
我的数据库版本是8.0.11,这是pom.xml里面的配置是这样的
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
连接
package com.gk.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DaoConnect {
public static Connection getConnect(){
Connection con = null;
//我的数据库版本是8.0.11,所以驱动的加载是com.mysql.cj.jdbc.Driver
//版本不同,加载驱动语句也不同,否则会报错
String driver = "com.mysql.cj.jdbc.Driver";
//数据库名是test
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String username = "root";
String password = "123456";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if(con != null){
System.out.println("连接成功");
}
return con;
}
}
查询
package com.gk.dao;
import com.gk.pojo.Commodity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class FindShop {
public List<Commodity> findAll(int currentPage, int pageSize) throws SQLException {
//查询某一页的数据
Connection con = DaoConnect.getConnect();
//sql语句查询
String sql = "select * from shop limit ?,? ";
PreparedStatement pre = con.prepareStatement(sql);
pre.setInt(1,(currentPage-1)*pageSize);//从第几条查询起
pre.setInt(2,pageSize);//总共查询几条
ResultSet re = pre.executeQuery();
List<Commodity> list = new ArrayList<>();
while(re.next()){
int id = re.getInt(1);
String name = re.getString(2);
String brand = re.getString(3);
String state = re.getString(4);
double praise = re.getDouble(5);
int sell = re.getInt(6);
double grade = re.getDouble(7);
//直接利用Commodity构造方法进行赋值
Commodity com = new Commodity(id,name,brand,state,praise,sell,grade);
//将值传入列表
list.add(com);
}
con.close();
re.close();
return list;
}
public int findRecordAll() throws SQLException {
//查询总共有几条记录
int count = 0;
Connection con = DaoConnect.getConnect();
String sql = "select count(*) from shop";
PreparedStatement pre = con.prepareStatement(sql);
ResultSet re = pre.executeQuery();
//只有一条数据,所以不用while
if(re.next()){
count = re.getInt(1);
}
con.close();
re.close();
return count;
}
}
- 设置页面的一些数据,如当前页,总记录数等
创建SetPageService.class
放在了service包里面
package com.gk.service;
import com.gk.dao.FindShop;
import com.gk.pojo.Commodity;
import com.gk.pojo.PageBean;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SetPageService {
public PageBean<Commodity> setPage(int currentPage , int pageSize){
FindShop find = new FindShop();
List<Commodity> list = new ArrayList<>();
try {
list = find.findAll(currentPage,pageSize);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
int total = 0;
try {
total = find.findRecordAll();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
PageBean<Commodity>page = new PageBean<>();
page.setPageSize(pageSize);
page.setCurrentPage(currentPage);
page.setTotalRecord(total);
//将查询到的记录存放到页面
page.setList(list);
return page;
}
}
- Servlet类(将页面的数据传到前端)
定义FindShopServlet.class
放在了servlet包里
package com.gk.servlet;
import com.gk.pojo.Commodity;
import com.gk.pojo.PageBean;
import com.gk.service.SetPageService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "FindShopServlet", urlPatterns = "/FindShopServlet")
public class FindShopServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String currentStr = request.getParameter("current");
//if(name == null){
//第一次加载的时候从前端没有传数据过来,要将当前页设置为1
if (currentStr == null) {
currentStr = "1";
}
//将字符串转换成int类型
int currentNum = Integer.parseInt(currentStr);
//定义一个页面对象
PageBean<Commodity> bean = new PageBean<>();
//定义一个页面传值的对象
SetPageService page = new SetPageService();
int pageSize = 2;
//将页面对象传进传值对象进行赋值
bean = page.setPage(currentNum, pageSize);
//请求转发
request.setAttribute("bean", bean);
//请求数据前后能够共享
request.getRequestDispatcher("Shop.jsp").forward(request, response);
}
}
- 前端页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored = "false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>商品列表</title>
</head>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
</script>
<body>
<table border="0">
<tr>
<th align="center"><p2>商品列表</p2></th>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td align="left">
<form action="FindShopServlet" method="post">
商品名称:<input type="text" name="name">
<input type="button" id="btn" value="查询">
</form>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td align="right">
<button><a href="ShoppingCar">进入购物车</a></button>
</td>
</tr>
</table>
<div style="height: 10px"></div>
<table border="1" cellspacing="0">
<tr>
<td>编号</td>
<td>名称</td>
<td>所属品牌</td>
<td>描述</td>
<td>价格</td>
<td>销量</td>
<td>买家评价</td>
<td>操作</td>
</tr>
<c:forEach var="d" items="${requestScope.bean.list}">
<tr>
<td>${d.id}</td>
<td>${d.name}</td>
<td>${d.brand}</td>
<td>${d.state}</td>
<td>${d.praise}</td>
<td>${d.sell}</td>
<td>${d.grade}</td>
<td>
<button>加入购物车</button>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="7">
当前:${requestScope.bean.currentPage}|${requestScope.bean.totalPage}
总数据量:${requestScope.bean.totalPage}
<input type="button" value="首页" onclick="toFirst()">
<input type="button" value="上一页" onclick="ToPreV()">
<input type="button" value="下一页" onclick="ToNext()">
<input type="button" value="尾页" onclick="toLast()">
</td>
</tr>
</table>
<script>
var currentNum=${requestScope.bean.currentPage};
var lastPage = ${requestScope.bean.totalPage};
function toFirst(){
window.location="FindShopServlet?current=1";
}
function ToPreV(){
if(currentNum == 1){
window.location="FindShopServlet?current=1";
}else{
window.location="FindShopServlet?current="+(currentNum-1);
}
}
function ToNext(){
if(currentNum == lastPage){
window.location="FindShopServlet?current="+lastPage;
}else{
window.location="FindShopServlet?current="+(currentNum+1);
}
}
function toLast(){
window.location="FindShopServlet?current="+lastPage;
}
</script>
</body>
</html>
最后要注意一点:加载页面的时候,地址栏不能是Shop.jsp而应该是FindShopServlet,否则会报错
如果有疑问,欢迎交流