javaweb多条件查寻笔记

1、通过表单将查询线索传递给后台的searchBooksServlet

   <form id="Form1" name="Form1"
action="${pageContext.request.contextPath}/servlet/searchBooksServlet"

method="post">

       在这里我用区间查询为例

<td height="22" align="center" bgColor="#f5fafe" class="ta_01">
价格区间(元):</td>
<td class="ta_01" bgColor="#ffffff"><input type="text"
name="minprice" size="10" value="" />- <input type="text"

name="maxprice" size="10" value="" /></td>

   2、在earchBooksServlet中获取表单数据

String minprice = request.getParameter("minprice");

String maxprice = request.getParameter("maxprice");

   调用业务逻辑,将其发送给Service。

BookServiceImpl bs = new BookServiceImpl();

扫描二维码关注公众号,回复: 5337356 查看本文章

List<Book> list = bs.searchBooks(minprice,maxprice);//将返回的数据放在集合中

//分发转向
request.setAttribute("books", list);//把list放入request对象中

request.getRequestDispatcher("/admin/products/list.jsp").forward(request, response);

3、sevice中主要调用dao中的方法

public List<Book> searchBooks(
String minprice, String maxprice) {
try {
return bookDao.searchBooks(id,category,name,minprice,maxprice);
} catch (SQLException e) {
e.printStackTrace();
}
return null;

}

4、dao

public List<Book> searchBooks(
String minprice, String maxprice) throws SQLException {
QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
String sql = "select * from book where 1=1";
List list = new ArrayList();

if(!"".equals(minprice.trim())){
sql+=" and price>?";
list.add(minprice.trim());
}
if(!"".equals(maxprice.trim())){
sql+=" and price< ?";
list.add(maxprice.trim());
}

return qr.query(sql, new BeanListHandler<Book>(Book.class),list.toArray());

}

注意:第四步会有报错:Wrong number of parameters: expected 2, was given 1 Query: select * from book where 1=1 and price>? and price< ? Parameters: [22222]

这是因为代码不全导致的,我一开始写时忘记写list.add(minprice.trim());点击查询控制台报错!

猜你喜欢

转载自blog.csdn.net/mddCSDN/article/details/80159862