帮我写一个Javaweb mvc模糊查询和多条件查询的分页显示的完整代码
时间: 2024-05-16 08:14:33 浏览: 252
模糊查询+分页
好的,这里是一个JavaWeb MVC模糊查询和多条件查询的分页显示的完整代码示例。
1. 创建数据库表
我们创建一个名为`person`的表,包含`id`,`name`,`age`,`email`四个字段。
```sql
CREATE TABLE person (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT NOT NULL,
email VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
```
2. 实现实体类
我们创建一个名为`Person`的实体类,对应`person`表的字段。
```java
public class Person {
private int id;
private String name;
private int age;
private String email;
// getter和setter方法省略
}
```
3. 实现DAO层接口
我们创建一个名为`PersonDao`的数据访问层接口,包含模糊查询和多条件查询两个方法。
```java
public interface PersonDao {
int countAll();
List<Person> findByKeyword(String keyword, int offset, int limit);
List<Person> findByCondition(String name, int age, String email, int offset, int limit);
}
```
4. 实现DAO层实现类
我们创建一个名为`PersonDaoImpl`的数据访问层实现类,实现`PersonDao`接口中的方法。
```java
public class PersonDaoImpl implements PersonDao {
private final Connection conn;
public PersonDaoImpl(Connection conn) {
this.conn = conn;
}
@Override
public int countAll() {
String sql = "SELECT COUNT(*) FROM person";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1);
} else {
return 0;
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public List<Person> findByKeyword(String keyword, int offset, int limit) {
String sql = "SELECT * FROM person WHERE name LIKE ? OR email LIKE ? LIMIT ?, ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "%" + keyword + "%");
stmt.setString(2, "%" + keyword + "%");
stmt.setInt(3, offset);
stmt.setInt(4, limit);
try (ResultSet rs = stmt.executeQuery()) {
List<Person> list = new ArrayList<>();
while (rs.next()) {
Person p = new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAge(rs.getInt("age"));
p.setEmail(rs.getString("email"));
list.add(p);
}
return list;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public List<Person> findByCondition(String name, int age, String email, int offset, int limit) {
String sql = "SELECT * FROM person WHERE 1=1";
List<Object> params = new ArrayList<>();
if (name != null && !name.isEmpty()) {
sql += " AND name LIKE ?";
params.add("%" + name + "%");
}
if (age > 0) {
sql += " AND age = ?";
params.add(age);
}
if (email != null && !email.isEmpty()) {
sql += " AND email LIKE ?";
params.add("%" + email + "%");
}
sql += " LIMIT ?, ?";
params.add(offset);
params.add(limit);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (int i = 0; i < params.size(); i++) {
stmt.setObject(i + 1, params.get(i));
}
try (ResultSet rs = stmt.executeQuery()) {
List<Person> list = new ArrayList<>();
while (rs.next()) {
Person p = new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAge(rs.getInt("age"));
p.setEmail(rs.getString("email"));
list.add(p);
}
return list;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
```
5. 实现Service层接口
我们创建一个名为`PersonService`的服务层接口,包含模糊查询和多条件查询两个方法。
```java
public interface PersonService {
int countAll();
List<Person> findByKeyword(String keyword, int page, int pageSize);
List<Person> findByCondition(String name, int age, String email, int page, int pageSize);
}
```
6. 实现Service层实现类
我们创建一个名为`PersonServiceImpl`的服务层实现类,实现`PersonService`接口中的方法,并调用`PersonDao`接口中的方法。
```java
public class PersonServiceImpl implements PersonService {
private final PersonDao dao;
public PersonServiceImpl(PersonDao dao) {
this.dao = dao;
}
@Override
public int countAll() {
return dao.countAll();
}
@Override
public List<Person> findByKeyword(String keyword, int page, int pageSize) {
int offset = (page - 1) * pageSize;
return dao.findByKeyword(keyword, offset, pageSize);
}
@Override
public List<Person> findByCondition(String name, int age, String email, int page, int pageSize) {
int offset = (page - 1) * pageSize;
return dao.findByCondition(name, age, email, offset, pageSize);
}
}
```
7. 实现Controller层
我们创建一个名为`PersonController`的控制层,实现模糊查询和多条件查询的接口,返回分页数据。
```java
@WebServlet("/person")
public class PersonController extends HttpServlet {
private static final long serialVersionUID = 1L;
private final PersonService service = new PersonServiceImpl(new PersonDaoImpl(ConnectionUtil.getConnection()));
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String keyword = request.getParameter("keyword");
String name = request.getParameter("name");
String ageStr = request.getParameter("age");
String email = request.getParameter("email");
int page = Integer.parseInt(request.getParameter("page"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
List<Person> list;
int count;
if (keyword != null && !keyword.isEmpty()) {
list = service.findByKeyword(keyword, page, pageSize);
count = service.countAll();
} else {
int age = ageStr != null && !ageStr.isEmpty() ? Integer.parseInt(ageStr) : 0;
list = service.findByCondition(name, age, email, page, pageSize);
count = name != null || age > 0 || email != null ? list.size() : service.countAll();
}
int pageCount = (int) Math.ceil(count * 1.0 / pageSize);
request.setAttribute("list", list);
request.setAttribute("count", count);
request.setAttribute("pageCount", pageCount);
request.setAttribute("page", page);
request.setAttribute("pageSize", pageSize);
request.getRequestDispatcher("/WEB-INF/views/person.jsp").forward(request, response);
}
}
```
8. 实现前端页面
我们创建一个名为`person.jsp`的前端页面,包含分页显示的表格和查询表单。
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Person List</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
border-bottom: 1px solid #ddd;
}
tr:hover {
background-color: #f5f5f5;
}
form {
display: inline-block;
}
label {
display: inline-block;
width: 60px;
text-align: right;
}
input, select {
width: 150px;
margin-right: 20px;
}
.pagination {
display: inline-block;
margin: 20px 0;
}
.pagination a {
color: black;
float: left;
padding: 8px 16px;
text-decoration: none;
transition: background-color .3s;
border: 1px solid #ddd;
margin: 0 4px;
}
.pagination a.active {
background-color: dodgerblue;
color: white;
border: 1px solid dodgerblue;
}
.pagination a:hover:not(.active) {
background-color: #ddd;
}
</style>
</head>
<body>
<h1>Person List</h1>
<form method="get" action="${pageContext.request.contextPath}/person">
<label>Keyword:</label>
<input type="text" name="keyword" value="${param.keyword}">
<input type="submit" value="Search">
</form>
<form method="get" action="${pageContext.request.contextPath}/person">
<label>Name:</label>
<input type="text" name="name" value="${param.name}">
<label>Age:</label>
<input type="number" name="age" value="${param.age}">
<label>Email:</label>
<input type="text" name="email" value="${param.email}">
<input type="submit" value="Search">
</form>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
<c:forEach var="p" items="${list}">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.age}</td>
<td>${p.email}</td>
</tr>
</c:forEach>
</table>
<div class="pagination">
<c:forEach var="i" begin="1" end="${pageCount}">
<a href="${pageContext.request.contextPath}/person?page=${i}&pageSize=${pageSize}&keyword=${param.keyword}&name=${param.name}&age=${param.age}&email=${param.email}" class="${page==i?'active':''}">${i}</a>
</c:forEach>
</div>
</body>
</html>
```
至此,我们就完成了JavaWeb MVC模糊查询和多条件查询的分页显示的完整代码示例。
阅读全文