提供一个Maven项目中,基于html,servlet,service,dao层之间进行数据回显并分页的功能,查询数据如下: 性别(gender) 地址(area) 年龄区间(age1,age2) 行业职位(occupation) 婚姻状况(marital_status) 提供servlet层(query),service层(实现queryserviceimpl接口),dao层(实现querydaoimpl接口)的完整代码
时间: 2023-09-29 17:07:18 浏览: 110
servlet实现的分页查询
以下是一个基于html,servlet,service,dao层之间进行数据回显并分页的功能的Maven项目,其中包含性别、地址、年龄区间、行业职位、婚姻状况等查询条件,具体实现可以参考以下代码:
1. 创建一个 Maven 项目,并添加依赖:
```xml
<dependencies>
<!-- JSP/Servlet API -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JDBC -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
</dependencies>
```
2. 创建一个 HTML 页面,包含查询条件和数据回显功能:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Query Page</title>
</head>
<body>
<form action="query" method="post">
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">-- Please Select --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<br/><br/>
<label for="area">Area:</label>
<input type="text" id="area" name="area"/>
<br/><br/>
<label for="age1">Age Range:</label>
<input type="number" id="age1" name="age1"/> - <input type="number" id="age2" name="age2"/>
<br/><br/>
<label for="occupation">Occupation:</label>
<input type="text" id="occupation" name="occupation"/>
<br/><br/>
<label for="marital_status">Marital Status:</label>
<select id="marital_status" name="marital_status">
<option value="">-- Please Select --</option>
<option value="Single">Single</option>
<option value="Married">Married</option>
<option value="Divorced">Divorced</option>
</select>
<br/><br/>
<input type="submit" value="Submit"/>
</form>
<br/><br/>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Area</th>
<th>Occupation</th>
<th>Marital Status</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.age}</td>
<td>${user.area}</td>
<td>${user.occupation}</td>
<td>${user.maritalStatus}</td>
</tr>
</c:forEach>
</tbody>
</table>
<br/><br/>
<c:if test="${currentPage > 1}">
<a href="query?page=${currentPage - 1}&keyword=${keyword}">Previous Page</a>
</c:if>
<c:if test="${currentPage < totalPages}">
<a href="query?page=${currentPage + 1}&keyword=${keyword}">Next Page</a>
</c:if>
</body>
</html>
```
在上述 HTML 页面中,我们使用了 JSP 标签库(JSTL)来进行数据回显和分页功能的实现。其中,`${users}` 对应的是从 Servlet 中传递过来的用户数据列表;`${currentPage}` 和 `${totalPages}` 分别是当前页码和总页数。
3. 创建一个 Servlet 类,接收查询条件并调用 Service 和 DAO 层进行数据查询:
```java
@WebServlet("/query")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private QueryService queryService = new QueryServiceImpl();
private static final int PAGE_SIZE = 10;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String gender = request.getParameter("gender");
String area = request.getParameter("area");
int age1 = Integer.parseInt(request.getParameter("age1"));
int age2 = Integer.parseInt(request.getParameter("age2"));
String occupation = request.getParameter("occupation");
String maritalStatus = request.getParameter("marital_status");
int page = Integer.parseInt(request.getParameter("page"));
List<User> users = queryService.query(gender, area, age1, age2, occupation, maritalStatus, page, PAGE_SIZE);
request.setAttribute("users", users);
request.setAttribute("currentPage", page);
request.setAttribute("totalPages", queryService.getTotalPages(gender, area, age1, age2, occupation, maritalStatus, PAGE_SIZE));
request.getRequestDispatcher("query.jsp").forward(request, response);
}
}
```
在上述 Servlet 类中,我们获取了来自 HTML 页面的查询条件,并通过 Service 层调用 DAO 层进行数据查询。同时,我们还计算出了当前页码和总页数,并将它们传递给 HTML 页面。
4. 创建一个 Service 接口和实现类,用于调用 DAO 层进行数据查询:
```java
public interface QueryService {
public List<User> query(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int page, int pageSize);
public int getTotalPages(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int pageSize);
}
public class QueryServiceImpl implements QueryService {
private QueryDao queryDao = new QueryDaoImpl();
public List<User> query(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int page, int pageSize) {
return queryDao.query(gender, area, age1, age2, occupation, maritalStatus, page, pageSize);
}
public int getTotalPages(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int pageSize) {
int totalRecords = queryDao.getTotalRecords(gender, area, age1, age2, occupation, maritalStatus);
return (totalRecords + pageSize - 1) / pageSize;
}
}
```
在上述 Service 层中,我们定义了两个方法,分别是 `query` 和 `getTotalPages`。其中,`query` 方法调用 DAO 层进行数据查询,并返回查询结果;`getTotalPages` 方法计算总页数。
5. 创建一个 DAO 接口和实现类,用于实现具体的数据查询:
```java
public interface QueryDao {
public List<User> query(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int page, int pageSize);
public int getTotalRecords(String gender, String area, int age1, int age2, String occupation, String maritalStatus);
}
public class QueryDaoImpl implements QueryDao {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
private static final String JDBC_USERNAME = "root";
private static final String JDBC_PASSWORD = "root";
private static final String QUERY_SQL = "SELECT * FROM users WHERE 1 = 1";
private static final String COUNT_SQL = "SELECT COUNT(*) FROM users WHERE 1 = 1";
public List<User> query(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int page, int pageSize) {
List<User> users = new ArrayList<User>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
String sql = buildQuerySql(gender, area, age1, age2, occupation, maritalStatus, page, pageSize);
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setGender(rs.getString("gender"));
user.setAge(rs.getInt("age"));
user.setArea(rs.getString("area"));
user.setOccupation(rs.getString("occupation"));
user.setMaritalStatus(rs.getString("marital_status"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch (Exception e) { }
try { stmt.close(); } catch (Exception e) { }
try { conn.close(); } catch (Exception e) { }
}
return users;
}
public int getTotalRecords(String gender, String area, int age1, int age2, String occupation, String maritalStatus) {
int totalRecords = 0;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
String sql = buildCountSql(gender, area, age1, age2, occupation, maritalStatus);
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
if (rs.next()) {
totalRecords = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch (Exception e) { }
try { stmt.close(); } catch (Exception e) { }
try { conn.close(); } catch (Exception e) { }
}
return totalRecords;
}
private String buildQuerySql(String gender, String area, int age1, int age2, String occupation, String maritalStatus, int page, int pageSize) {
StringBuilder sb = new StringBuilder(QUERY_SQL);
if (StringUtils.isNotEmpty(gender)) {
sb.append(" AND gender = '" + gender + "'");
}
if (StringUtils.isNotEmpty(area)) {
sb.append(" AND area LIKE '%" + area + "%'");
}
if (age1 > 0 && age2 > 0) {
sb.append(" AND age BETWEEN " + age1 + " AND " + age2);
}
if (StringUtils.isNotEmpty(occupation)) {
sb.append(" AND occupation LIKE '%" + occupation + "%'");
}
if (StringUtils.isNotEmpty(maritalStatus)) {
sb.append(" AND marital_status = '" + maritalStatus + "'");
}
sb.append(" LIMIT " + (page - 1) * pageSize + ", " + pageSize);
return sb.toString();
}
private String buildCountSql(String gender, String area, int age1, int age2, String occupation, String maritalStatus) {
StringBuilder sb = new StringBuilder(COUNT_SQL);
if (StringUtils.isNotEmpty(gender)) {
sb.append(" AND gender = '" + gender + "'");
}
if (StringUtils.isNotEmpty(area)) {
sb.append(" AND area LIKE '%" + area + "%'");
}
if (age1 > 0 && age2 > 0) {
sb.append(" AND age BETWEEN " + age1 + " AND " + age2);
}
if (StringUtils.isNotEmpty(occupation)) {
sb.append(" AND occupation LIKE '%" + occupation + "%'");
}
if (StringUtils.isNotEmpty(maritalStatus)) {
sb.append(" AND marital_status = '" + maritalStatus + "'");
}
return sb.toString();
}
}
```
在上述 DAO 层中,我们定义了两个方法,分别是 `query` 和 `getTotalRecords`。其中,`query` 方法根据查询条件进行数据查询,并返回查询结果;`getTotalRecords` 方法计算总记录数。
至此,基于html,servlet,service,dao层之间进行数据回显并分页的功能的Maven项目已经完成了。
阅读全文