编写一个servlet,在servlet中查询goods表中的记录,并在showMoveGoods.jsp页面中逆序显示偶数行的记录。在本例中需要使用实体类goods,但需要为Goods添加一个属性rowno封装行号。
时间: 2024-01-22 07:21:09 浏览: 74
首先,我们需要编写一个servlet,查询goods表中的记录,并为每一行添加一个rowno属性封装行号:
```
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ShowMoveGoodsServlet")
public class ShowMoveGoodsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Goods> goodsList = new ArrayList<>();
try {
conn = DBUtil.getConnection();
stmt = conn.prepareStatement("SELECT * FROM goods ORDER BY id DESC");
rs = stmt.executeQuery();
int rowno = 0;
while (rs.next()) {
Goods goods = new Goods();
goods.setId(rs.getInt("id"));
goods.setName(rs.getString("name"));
goods.setPrice(rs.getDouble("price"));
goods.setRowno(++rowno);
goodsList.add(goods);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, stmt, rs);
}
request.setAttribute("goodsList", goodsList);
request.getRequestDispatcher("showMoveGoods.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
在这个servlet中,我们首先获取数据库连接,然后查询goods表中的记录,并为每一行添加一个rowno属性封装行号。最后将goodsList设置为request属性并转发到showMoveGoods.jsp页面。
接下来,我们需要编写一个showMoveGoods.jsp页面,逆序显示偶数行的记录:
```
<%@ 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>移动商品展示页面</title>
</head>
<body>
<h1>移动商品列表</h1>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<c:forEach items="${goodsList}" var="goods" varStatus="status">
<c:if test="${status.index % 2 == 0}">
<tr>
<td>${goods.rowno}</td>
<td>${goods.name}</td>
<td>${goods.price}</td>
</tr>
</c:if>
</c:forEach>
</tbody>
</table>
</body>
</html>
```
在这个页面中,我们使用了JSTL标签库中的c:forEach标签遍历goodsList中的每一个goods对象,并使用c:if标签判断是否为偶数行。如果是偶数行,则将该行记录逆序显示在表格中。
最后,我们需要在web.xml中配置servlet和servlet-mapping:
```
<servlet>
<servlet-name>ShowMoveGoodsServlet</servlet-name>
<servlet-class>ShowMoveGoodsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowMoveGoodsServlet</servlet-name>
<url-pattern>/ShowMoveGoodsServlet</url-pattern>
</servlet-mapping>
```
这样就完成了一个查询goods表中的记录,并在showMoveGoods.jsp页面中逆序显示偶数行的记录的示例。
阅读全文