需求:当搜索框为空时,查询数据库所有商品,输入商品名时,进行模糊查询
实现思路:运用表单提交的方式访问Servlet,然后将输入的值传到后台,运用sql语句对数据库进行查询。
具体来看代码吧!
搜索框代码
<div class="sousuo">
<form action="${ctx}/chaXun" methed="get">
<input type="text" id="input" autocomplete="off" name="productName" title="请输入商品名">
<input type="submit" id="sousuo_kuan" value="搜索">
</form>
</div>
<!--使用盒子存放查询到的结果-->
<div class="bigbox"><!--这是大盒子-->
<c:forEach var="item" items="${list}" varStatus="aa">
<div class="minbox"><!--这是小盒子-->
<span class="imgLink">
<a href="${ctx }/ProductDetailsServlet?id=${item.id }" ><img src="${item.imgUrl}" /></a>
</span>
<p class="price">
<span class="pricedetail">
¥
<strong>${item.price }</strong>
</span>
<span class="postalicon">包邮</span>
</p>
<p class="shopName">
</p>
</div>
</div>
</c:forEach>
</div>
autocomplete="off"表示规定输入字段不启用自动完成功能
点击搜索按钮时就到了后台
下面是Servlet代码
//进行编码为utf-8
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取Session对象
HttpSession session=request.getSession();
//创建ProductService类
ProductService service=new ProductService();
String productName=request.getParameter("productName");
//调用ProductService类的方法
List<Product> list=service.getUserList(productName);
//通过商品名遍历商品列表
for(Product pro:list) {
//获取商品Id
int productId=pro.getId();
//将商品ID存到Session中
session.setAttribute("productId", productId);
}
//将商品信息存到Request中
request.setAttribute("list", list);
//进行页面跳转
request.getRequestDispatcher("/test/findProduct.jsp").forward(request, response);
然后到Service层
/*
* 通过商品名查询,如果为空则返回所有
*/
public List<Product> getUserList(String productName){
List<Product> result = null;
//输入的内容是否为空进行判断,如果为空,就返回所有
if(productName == null || productName.trim().equals("")) {
//查询所有商品
result = dao.findAll();
return result;
}
//查询模糊查询商品
result = (List<Product>) this.dao.getProductName(productName);
return result;
}
最后到Dao层
/*
* 查询所有商品
*/
public List<Product> findAll(){
List<Product> list=null;
String sql="select * from product";
try {
list = (List<Product>) runner.query(sql, new BeanListHandler(Product.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/*
* 根据商品名模糊查询
*/
public List<Product> getProductName(String productName){
List<Product> list=null;
String sql="select * from product where productName like ?";
try {
list=(List<Product>) runner.query(sql, new BeanListHandler(Product.class),"%"+productName+"%");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
查询功能就这样实现了。记得点赞哦!您的点赞是我写作的动力