CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

[Java Web] Lọc, phân trang, tìm kiếm dữ liệu với SQL Server trong JSP Servlet

Đăng lúc: 09:24 AM - 23/02/2024 bởi Charles Chung - 943

Trong bài này tôi sẽ hướng dẫn các bạn cách lọc, tìm kiếm theo các tiêu chí, phân trang dữ liệu với SQL Server trong JSP Servlet

1. Chuẩn bị dữ liệu

Chúng ta vẫn sử dụng cơ sở dữ liệu của bài trước, tuy nhiên sẽ bổ sung thêm bảng Category và khóa ngoại trong bảng Flower, hình mô ta như sau:

Tải tệp script sql tại đây

2. Các thao tác trong bài demo

  • Lọc sản phẩm theo danh mục (loại)
  • Tìm kiếm sản phẩm theo danh mục và tên
  • Tìm kiếm sản phẩm theo khoảng giá
  • Phân trang sản phẩm theo danh mục

3. Các bước thực hiện

Bước 1: Trong Eclipse tạo project Dynamic Web Project "JSPServletSession07"

Bước 2: Convert project sang Maven Project và cấu hình file pom.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<dependencies>
		<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>12.5.0.jre11-preview</version>
		</dependency>
		<!--https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload-->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.13.0</version>
		</dependency>
</dependencies>

Bước 3: Tạo các trang jsp, các giao diện, lớp theo cấu trúc mô tả sau

Bước 4: Code cho các trang jsp và các lớp, servlet.

- Trang index.jsp (hiển thị menu và các trang tương ứng)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cửa hàng hoa tươi BKAP</title>
<link rel="stylesheet"
	href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" />
	<script src="ckeditor/ckeditor.js"></script>
<style>
#content {
	padding: 10px;
}
</style>
</head>
<body>
	<div class="container">
		<nav class="nav">
			<a class="nav-link active" href="FlowerServlet">Trang chủ</a> |
			<a class="nav-link" href="FlowerServlet?action=category">Lọc theo danh mục</a> |
			<a class="nav-link" href="FlowerServlet?action=searchname">Tìm kiếm theo tên</a> |
			<a class="nav-link" href="FlowerServlet?action=searchprice">Tìm kiếm theo giá</a> |
			<a class="nav-link" href="FlowerServlet?action=paging">Phân trang</a> 
		</nav>
		<hr>
		<div id="content">
			<c:if test="${!(empty param.page)}">
				<jsp:include page="${param.page}.jsp"></jsp:include>
			</c:if>
		</div>
	</div>
	<!-- Optional JavaScript -->
	<!-- jQuery first, then Popper.js, then Bootstrap JS -->
	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
	<script
		src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"></script>
	<script
		src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"></script>
		
</body>
</html>

- Trang flowertables.jsp (hiển thị tất cả loài hoa)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<h4>Hiển thị tất cả hoa</h4>
<span style="color:blue">${msg}</span>
<p><a href="index.jsp?page=add" class="btn btn-primary">Thêm mới</a></p>
<table class="table table-bordered">
	<tr>
		<th>Mã số</th>
		<th>Tên hoa</th>
		<th>Giá</th>
		<th>Ảnh</th>
		<th>Ngày tạo</th>
		<th>Tình trạng</th>
		<th></th>
	</tr>
	<c:forEach items="${flowers}" var="f">
		<tr>
			<td>${f.flowerId}</td>
			<td>${f.flowerName}</td>
			<td>${f.price}</td>
			<td><img src="images/${f.picture}" width="100"/></td>
			<td><f:formatDate value="${f.createDate}" pattern="dd/MM/yyyy"/> </td>
			<td><c:choose>
				<c:when test="${f.active==true}">
					Còn hàng
				</c:when>
				<c:otherwise>
					Hết hàng
				</c:otherwise>
			</c:choose>
			</td>
			<th>
				<a href="FlowerServlet?action=edit&flowerid=${f.flowerId}" class="btn btn-info">Sửa</a>
				<a href="FlowerServlet?action=delete&flowerid=${f.flowerId}" class="btn btn-danger" onclick="return confirm('Bạn có muốn xóa không?')">Xóa</a>
				<a href="FlowerServlet?action=detail&flowerid=${f.flowerId}" class="btn btn-success">Chi tiết</a>
			</th>
		</tr>
	</c:forEach>
</table>

- Trang flowercategories.jsp (hiển thị kết quả lọc theo danh mục loại hoa)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<h4>Chọn loại hoa</h4>
<form action="" method="post">
	<select name="cateid" onchange="forms[0].submit()" class="form-control">
		<option value="0">---------Hiển thị tất cả-----------</option>
		<c:forEach var="c" items="${categories}">
			<c:choose>
				<c:when test="${c.categoryId==cateid}">
					<option value="${c.categoryId}" selected>${c.categoryName}</option>
				</c:when>
				<c:otherwise>
					<option value="${c.categoryId}">${c.categoryName}</option>
				</c:otherwise>
			</c:choose>
		</c:forEach>
	</select>
</form>
<hr>
<table class="table table-bordered">
	<tr>
		<th>Mã số</th>
		<th>Tên hoa</th>
		<th>Giá</th>
		<th>Ảnh</th>
		<th>Ngày tạo</th>
		<th>Tình trạng</th>
	</tr>
	<c:forEach items="${flowers}" var="f">
		<tr>
			<td>${f.flowerId}</td>
			<td>${f.flowerName}</td>
			<td>${f.price}</td>
			<td><img src="images/${f.picture}" width="100" /></td>
			<td><f:formatDate value="${f.createDate}" pattern="dd/MM/yyyy" />
			</td>
			<td><c:choose>
					<c:when test="${f.active==true}">
					Còn hàng
				</c:when>
					<c:otherwise>
					Hết hàng
				</c:otherwise>
				</c:choose></td>
		</tr>
	</c:forEach>
</table>

- Trang flowersearch.jsp (hiển thị kết quả tìm kiếm theo danh mục và tên)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<h4>Tìm kiếm theo loại và tên</h4>
<form action="" method="post">
	Chọn loại hoa <select name="cateid">
		<option value="0">---------Hiển thị tất cả-----------</option>
		<c:forEach var="c" items="${categories}">
			<c:choose>
				<c:when test="${c.categoryId==cateid}">
					<option value="${c.categoryId}" selected>${c.categoryName}</option>
				</c:when>
				<c:otherwise>
					<option value="${c.categoryId}">${c.categoryName}</option>
				</c:otherwise>
			</c:choose>
		</c:forEach>
	</select>
	 <input type="text" name="name" placeholder="Nhập tên cần tìm"/>
	 <button class="btn btn-primary key">Tìm</button>
</form>
<hr>
<table class="table table-bordered">
	<tr>
		<th>Mã số</th>
		<th>Tên hoa</th>
		<th>Giá</th>
		<th>Ảnh</th>
		<th>Ngày tạo</th>
		<th>Tình trạng</th>
	</tr>
	<c:forEach items="${flowers}" var="f">
		<tr>
			<td>${f.flowerId}</td>
			<td>${f.flowerName}</td>
			<td>${f.price}</td>
			<td><img src="images/${f.picture}" width="100" /></td>
			<td><f:formatDate value="${f.createDate}" pattern="dd/MM/yyyy" />
			</td>
			<td><c:choose>
					<c:when test="${f.active==true}">
					Còn hàng
				</c:when>
					<c:otherwise>
					Hết hàng
				</c:otherwise>
				</c:choose></td>
		</tr>
	</c:forEach>
</table>

- Trang flowersearchprice.jsp (hiển thị kết quả tìm kiếm theo khoảng giá)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<h4>Tìm kiếm theo khoảng giá</h4>
<form action="" method="post">
	Nhập giá từ <input type="number" name="fromprice"/> đến giá 
	 <input type="number" name="toprice"/>
	 <button class="btn btn-primary key">Tìm</button>
</form>
<hr>
<table class="table table-bordered">
	<tr>
		<th>Mã số</th>
		<th>Tên hoa</th>
		<th>Giá</th>
		<th>Ảnh</th>
		<th>Ngày tạo</th>
		<th>Tình trạng</th>
	</tr>
	<c:forEach items="${flowers}" var="f">
		<tr>
			<td>${f.flowerId}</td>
			<td>${f.flowerName}</td>
			<td>${f.price}</td>
			<td><img src="images/${f.picture}" width="100" /></td>
			<td><f:formatDate value="${f.createDate}" pattern="dd/MM/yyyy" />
			</td>
			<td><c:choose>
					<c:when test="${f.active==true}">
					Còn hàng
				</c:when>
					<c:otherwise>
					Hết hàng
				</c:otherwise>
				</c:choose></td>
		</tr>
	</c:forEach>
</table>

- Trang flowerpaging.jsp (hiển thị kết quả phân trang theo danh mục)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<h4>Phân trang theo loại hoa</h4>
<form action="FlowerServlet?action=paging" method="post">
	Chọn loại hoa <select name="cateid" onchange="forms[0].submit()">
		<option value="0">---------Hiển thị tất cả-----------</option>
		<c:forEach var="c" items="${categories}">
			<c:choose>
				<c:when test="${c.categoryId==cateid}">
					<option value="${c.categoryId}" selected>${c.categoryName}</option>
				</c:when>
				<c:otherwise>
					<option value="${c.categoryId}">${c.categoryName}</option>
				</c:otherwise>
			</c:choose>
		</c:forEach>
	</select>
</form>
<hr>
<table class="table table-bordered">
	<tr>
		<th>Mã số</th>
		<th>Tên hoa</th>
		<th>Giá</th>
		<th>Ảnh</th>
		<th>Ngày tạo</th>
		<th>Tình trạng</th>
	</tr>
	<c:forEach items="${flowers}" var="f">
		<tr>
			<td>${f.flowerId}</td>
			<td>${f.flowerName}</td>
			<td>${f.price}</td>
			<td><img src="images/${f.picture}" width="100" /></td>
			<td><f:formatDate value="${f.createDate}" pattern="dd/MM/yyyy" />
			</td>
			<td><c:choose>
					<c:when test="${f.active==true}">
					Còn hàng
				</c:when>
					<c:otherwise>
					Hết hàng
				</c:otherwise>
				</c:choose></td>
		</tr>
	</c:forEach>
</table>
Trang:
<c:forEach var="i" begin="1" end="${totalpage}">
	<c:choose>
		<c:when test="${i==currentpage}">
			<span> ${i} </span>
		</c:when>
		<c:otherwise>
			<a href="FlowerServlet?action=paging&cateid=${param.cateid}&pageno=${i}"> ${i} </a>
		</c:otherwise>
	</c:choose>
</c:forEach>

- Lớp com.bkap.entities/Category.java (biểu diễn dữ liệu tương ứng với bảng Category)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.bkap.entities;

public class Category {
	private int categoryId;
	private String categoryName;
	private int parentId;
	public Category() {
		
	}
	public Category(int categoryId, String categoryName, int parentId) {
		super();
		this.categoryId = categoryId;
		this.categoryName = categoryName;
		this.parentId = parentId;
	}
	public int getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}
	public String getCategoryName() {
		return categoryName;
	}
	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}
	public int getParentId() {
		return parentId;
	}
	public void setParentId(int parentId) {
		this.parentId = parentId;
	}
	
}

- Lớp com.bkap.entities/Flower.java (biểu diễn dữ liệu tương ứng với bảng Flower)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
package com.bkap.entities;

import java.sql.Date;

public class Flower {
	private String flowerId;
	private String flowerName;
	private String unit;
	private float price;
	private float priceOld;
	private String brief;
	private String description;
	private String picture;
	private int categoryId;
	private Date createDate;
	private boolean active;
	public Flower() {
		
	}
	public Flower(String flowerId, String flowerName, String unit, float price, float priceOld, String brief,
			String description, String picture,int categoryId, Date createDate, boolean active) {
		super();
		this.flowerId = flowerId;
		this.flowerName = flowerName;
		this.unit = unit;
		this.price = price;
		this.priceOld = priceOld;
		this.brief = brief;
		this.description = description;
		this.picture = picture;
		this.categoryId=categoryId;
		this.createDate = createDate;
		this.active = active;
	}

	public String getFlowerId() {
		return flowerId;
	}
	public void setFlowerId(String flowerId) {
		this.flowerId = flowerId;
	}
	public String getFlowerName() {
		return flowerName;
	}
	public void setFlowerName(String flowerName) {
		this.flowerName = flowerName;
	}
	public String getUnit() {
		return unit;
	}
	public void setUnit(String unit) {
		this.unit = unit;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public float getPriceOld() {
		return priceOld;
	}
	public void setPriceOld(float priceOld) {
		this.priceOld = priceOld;
	}
	public String getBrief() {
		return brief;
	}
	public void setBrief(String brief) {
		this.brief = brief;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getPicture() {
		return picture;
	}
	public void setPicture(String picture) {
		this.picture = picture;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	public boolean isActive() {
		return active;
	}
	public void setActive(boolean active) {
		this.active = active;
	}
	public int getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}
	
}

- Lớp com.bkap.entities/FlowerPage.java (biểu diễn dữ liệu kết quả phân trang)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.bkap.entities;

import java.util.List;

public class FlowerPage {
	private List<Flower> flowers;
	private int totalPages;
	private int pageSize;
	private int currentPage;
	public FlowerPage() {
		// TODO Auto-generated constructor stub
	}
	public FlowerPage(List<Flower> flowers, int totalPages, int pageSize, int currentPage) {
		super();
		this.flowers = flowers;
		this.totalPages = totalPages;
		this.pageSize = pageSize;
		this.currentPage = currentPage;
	}
	public List<Flower> getFlowers() {
		return flowers;
	}
	public void setFlowers(List<Flower> flowers) {
		this.flowers = flowers;
	}
	public int getTotalPages() {
		return totalPages;
	}
	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	
}

- Lớp com.bkap.dao/DatabaseUtil.java (biểu diễn kết nối cơ sở dữ liệu)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.bkap.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseUtil {
	private static String username="sa";
	private static String password="123465";
	private static String url="jdbc:sqlserver://localhost:1433;databaseName=FlowerSun;Encrypt=True;TrustServerCertificate=True";
	public static Connection getConnect() {
		Connection con=null;
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			con=DriverManager.getConnection(url,username, password);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
}

- Giao diện com.bkap.dao/CategoryDao.java (biểu diễn nghiệp vụ của Category)

1
2
3
4
5
6
7
8
9
package com.bkap.dao;

import java.util.List;

import com.bkap.entities.Category;

public interface CategoryDao {
	public List<Category> getAll();
}

- Giao diện com.bkap.dao/FlowerDao.java (biểu diễn nghiệp vụ của Flower)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.bkap.dao;

import java.util.List;

import com.bkap.entities.Flower;
import com.bkap.entities.FlowerPage;

public interface FlowerDao {
	public List<Flower> search(int cateid);
	public List<Flower> search(int cateid,String name);
	public List<Flower> search(float fromPrice,float toPrice);
	public FlowerPage paging(int cateid, int pageno, int pagesize);
}

- Lớp com.bkap.dao/CategoryImpl.java (biểu diễn thực thi nghiệp vụ của CategoryDao)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.bkap.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.bkap.entities.Category;

public class CategoryImpl implements CategoryDao {
	private Connection con = null;

	public CategoryImpl() {
		this.con = DatabaseUtil.getConnect();
	}

	@Override
	public List<Category> getAll() {
		List<Category> data=new ArrayList<>();
		try {
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("select * from Categories");
			while (rs.next()) {
				Category c=new Category(rs.getInt("categoryid"), rs.getString("categoryname"), rs.getInt("parentid"));
				data.add(c);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return data;
	}

}

- Lớp com.bkap.dao/FlowerImpl.java (biểu diễn thực thi nghiệp vụ của FlowerDao)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.bkap.dao;

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.bkap.entities.Flower;
import com.bkap.entities.FlowerPage;

public class FlowerImpl implements FlowerDao {
	private Connection con = null;

	public FlowerImpl() {
		this.con = DatabaseUtil.getConnect();
	}

	@Override
	public List<Flower> search(int cateid) {
		List<Flower> data = new ArrayList<>();
		PreparedStatement pst = null;
		try {
			if (cateid == 0) {
				pst = con.prepareStatement("select * from Flowers");
			} else {
				pst = con.prepareStatement("select * from Flowers where categoryid=?");
				pst.setInt(1, cateid);
			}
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				Flower f = new Flower(rs.getString("flowerid"), rs.getString("flowername"), rs.getString("unit"),
						rs.getFloat("price"), rs.getFloat("priceold"), rs.getString("brief"),
						rs.getString("description"), rs.getString("picture"), rs.getInt("categoryid"),
						rs.getDate("createdate"), rs.getBoolean("active"));
				data.add(f);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return data;
	}

	@Override
	public List<Flower> search(int cateid, String name) {
		List<Flower> data = new ArrayList<>();
		PreparedStatement pst = null;
		try {
			if (cateid == 0) {
				pst = con.prepareStatement("select * from Flowers where flowername like ?");
				pst.setString(1, "%" + name + "%");
			} else {
				pst = con.prepareStatement("select * from Flowers where categoryid=? and flowername like ?");
				pst.setInt(1, cateid);
				pst.setString(2, "%" + name + "%");
			}
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				Flower f = new Flower(rs.getString("flowerid"), rs.getString("flowername"), rs.getString("unit"),
						rs.getFloat("price"), rs.getFloat("priceold"), rs.getString("brief"),
						rs.getString("description"), rs.getString("picture"), rs.getInt("categoryid"),
						rs.getDate("createdate"), rs.getBoolean("active"));
				data.add(f);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return data;
	}

	@Override
	public List<Flower> search(float fromPrice, float toPrice) {
		List<Flower> data = new ArrayList<>();
		PreparedStatement pst = null;
		try {
			if (fromPrice == 0 && toPrice > 0) {
				pst = con.prepareStatement("select * from Flowers where price<=?");
				pst.setFloat(1, toPrice);
			} else if (fromPrice > 0 && toPrice == 0) {
				pst = con.prepareStatement("select * from Flowers where price>=?");
				pst.setFloat(1, fromPrice);
			} else {
				pst = con.prepareStatement("select * from Flowers where price>=? and price<=?");
				pst.setFloat(1, fromPrice);
				pst.setFloat(2, toPrice);
			}
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				Flower f = new Flower(rs.getString("flowerid"), rs.getString("flowername"), rs.getString("unit"),
						rs.getFloat("price"), rs.getFloat("priceold"), rs.getString("brief"),
						rs.getString("description"), rs.getString("picture"), rs.getInt("categoryid"),
						rs.getDate("createdate"), rs.getBoolean("active"));
				data.add(f);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return data;
	}

	@Override
	public FlowerPage paging(int cateid, int pageno, int pagesize) {
		FlowerPage data = null;
		List<Flower> flowers = new ArrayList<>();
		PreparedStatement pst = null;
		try {
			if (cateid == 0) {
				pst = con.prepareStatement(
						"select * from Flowers order by price offset (?-1)*? rows fetch next ? rows only");
				pst.setInt(1, pageno);
				pst.setInt(2, pagesize);
				pst.setInt(3, pagesize);
			} else {
				pst = con.prepareStatement(
						"select * from Flowers where categoryid=? order by price offset (?-1)*? rows fetch next ? rows only");
				pst.setInt(1, cateid);
				pst.setInt(2, pageno);
				pst.setInt(3, pagesize);
				pst.setInt(4, pagesize);
			}
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				Flower f = new Flower(rs.getString("flowerid"), rs.getString("flowername"), rs.getString("unit"),
						rs.getFloat("price"), rs.getFloat("priceold"), rs.getString("brief"),
						rs.getString("description"), rs.getString("picture"), rs.getInt("categoryid"),
						rs.getDate("createdate"), rs.getBoolean("active"));
				flowers.add(f);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		int rows = countFlowers(cateid);
		int totalpage = (rows % pagesize == 0) ? rows / pagesize : (rows / pagesize) + 1;
		data = new FlowerPage(flowers, totalpage, pagesize, pageno);
		return data;
	}

	private int countFlowers(int cateid) {
		int total = 0;
		PreparedStatement pst = null;
		try {
			if (cateid == 0) {
				pst = con.prepareStatement("select count(*) as totalFlowers from Flowers");
			} else {
				pst = con.prepareStatement("select count(*) as totalFlowers from Flowers where categoryid=?");
				pst.setInt(1, cateid);
			}
			ResultSet rs = pst.executeQuery();
			if (rs.next()) {
				total = rs.getInt("totalFlowers");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return total;
	}
}

- Phương thức doGet() trong lớp com.bkap.servlets/FlowerServlet.java (biểu diễn xử lý các nghiệp vụ của ứng ứng dụng)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF8");
		FlowerDao flowerDao = new FlowerImpl();
		CategoryDao categoryDao=new CategoryImpl();
		String action = request.getParameter("action");
		if (action == null) {
			request.setAttribute("flowers", flowerDao.search(0));
			request.getRequestDispatcher("index.jsp?page=flowertables").forward(request, response);
		} else if(action.equals("category")) {
			var categories=categoryDao.getAll();
			int cateid=request.getParameter("cateid")==null?0:Integer.parseInt(request.getParameter("cateid"));
			request.setAttribute("categories",categories );
			request.setAttribute("cateid", cateid);
			request.setAttribute("flowers", flowerDao.search(cateid));
			request.getRequestDispatcher("index.jsp?page=flowercategories").forward(request, response);
		} else if(action.equals("searchname")) {
			var categories=categoryDao.getAll();
			int cateid=request.getParameter("cateid")==null?0:Integer.parseInt(request.getParameter("cateid"));
			String name=request.getParameter("name");
			request.setAttribute("categories",categories );
			request.setAttribute("cateid", cateid);
			request.setAttribute("flowers", flowerDao.search(cateid,name));
			request.getRequestDispatcher("index.jsp?page=flowersearch").forward(request, response);
		}else if(action.equals("searchprice")) {
			float fromprice=request.getParameter("fromprice")==null || request.getParameter("fromprice").equals("")?0:Float.parseFloat(request.getParameter("fromprice"));
			float toprice=request.getParameter("toprice")==null || request.getParameter("toprice").equals("")?0:Float.parseFloat(request.getParameter("toprice"));
			request.setAttribute("flowers", flowerDao.search(fromprice,toprice));
			request.getRequestDispatcher("index.jsp?page=flowersearchprice").forward(request, response);
		}else if(action.equals("paging")) {
			var categories=categoryDao.getAll();
			int cateid=request.getParameter("cateid")==null || request.getParameter("cateid").equals("")?0:Integer.parseInt(request.getParameter("cateid"));
			int pageno=request.getParameter("pageno")==null?1:Integer.parseInt(request.getParameter("pageno"));
			int pagesize=3;
			FlowerPage flowerPage=flowerDao.paging(cateid, pageno, pagesize);
			request.setAttribute("categories",categories );
			request.setAttribute("cateid", cateid);
			request.setAttribute("flowers", flowerPage.getFlowers());
			request.setAttribute("totalpage", flowerPage.getTotalPages());
			request.setAttribute("currentpage", flowerPage.getCurrentPage());
			request.getRequestDispatcher("index.jsp?page=flowerpaging").forward(request, response);
}

Bước 5: Run và kiểm tra kết quả

- Trang hiển thị kết quả lọc theo danh mục

- Trang hiển thị kết quả tìm kiếm theo tên và danh mục

- Trang hiển thị kết quả tìm kiếm theo khoảng giá

- Trang hiển thị kết quả phân trang theo danh mục

Link tải source code

Video

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ