javaweb多条件查寻笔记

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

   

action="${pageContext.request.contextPath}/servlet/searchBooksServlet"

method="post">

       在这里我用区间查询为例


价格区间(元):
name="minprice" size="10" value="" />-

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

   2、在earchBooksServlet中获取表单数据

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

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

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

BookServiceImpl bs = new BookServiceImpl();

List 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 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 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.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());点击查询控制台报错!

你可能感兴趣的:(Javaweb笔记)