前台代码
<c:forEach items="${list}" var="category">
<tr οnmοuseοver="this.style.backgroundColor = 'white'"
οnmοuseοut="this.style.backgroundColor = '#F5FAFE';">
<td style="CURSOR: hand; HEIGHT: 22px" align="center"
width="18%">
${category.cid}</td>//获取其cid
<td style="CURSOR: hand; HEIGHT: 22px" align="center"
width="17%">
${category.cname}</td>//获取category里的came
<td align="center" style="HEIGHT: 22px"><a
href=
"${ pageContext.request.contextPath }/category?method=toUpdate&&cid=${category.cid}">
<img
src="${pageContext.request.contextPath}/images/i_edit.gif"
border="0" style="CURSOR: hand">
</a></td>
<td align="center" style="HEIGHT: 22px"><a href="
${pageContext.request.contextPath}/category?cid=${category.cid}&&method=delete">
<img src="${pageContext.request.contextPath}/images/i_del.gif"
width="16" height="16" border="0" style="CURSOR: hand">
</a></td>
</tr>
</c:forEach>
Servlet
public void list(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int currentPage = 1;
PageUtils<Category> page = new PageUtils<Category>();//调用工具类进行分页查询
List list = page.getAllCategories(req.getParameter("currentPage"),
"select * from category limit ?,?", Category.class);
req.setAttribute("list", list);
req.setAttribute("currentPage", page.getCurrentPage());
req.setAttribute("maxPage", page.getMaxPage("category"));
req.setAttribute("totalCount", page.getTotalCount());
req.getRequestDispatcher("/admin/category/list.jsp").forward(req, resp);
}
Service
public class CategoryService {
private CategoryDao cd = new CategoryDao();
public List<Category> findAllCategories(int currentPage,int pageSize){
int start = (currentPage - 1) * pageSize;
try {
return cd.findAllCategories(start, pageSize);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Dao
/**
*
* @param start 起始位置
* @param pageSize 每页显示条数
* @return
* @throws SQLException
* 因为是查询类似列表的东西 所以需要使用List <>集合 导入参数start pagesize 。
* 写 sql语句查询category里的数据
* limit ?,?是限制参数
* QueryRunner中提供对sql语句操作的API
它主要有三个方法
query() 用于执行select
update() 用于执行insert/update/delete
batch() 批处理
*/
public List<Category> findAllCategories(int start,int pageSize) throws SQLException{
String sql = "select * from category limit ?,?";
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
return qr.query(sql, new BeanListHandler<Category>(Category.class), start,pageSize);
}
下面是封装类
public class Category {
private String cid;
private String cname;
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}
综述: 在前台提交请求或者表单,跟servlet绑定的代码做出相应发送请求或数据到servlet层进行处理