第六篇——模糊查询
1、接口
List<Product> queryLike(String key);
2、dao
public List<Product> queryLike(String key) {
String sql="select * from product where name like ?";
List<Product> list=new ArrayList();
try {
ps = ConnectionDatabase.getConnection().prepareStatement(sql);
ps.setString(1, "%"+key+"%");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Product p=new Product();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAddr(rs.getString("addr"));
p.setPrice(rs.getDouble("price"));
list.add(p);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
测试
@Test
public void dao() {
List<Product> list = DaoFactory.getProductDao().queryLike("1");
System.out.println(list);
}
3、service
private void queryLikeService(HttpServletRequest request, HttpServletResponse response) {
String name=request.getParameter("name");
List<Product> list=DaoFactory.getProductDao().queryLike(name);
try {
if (list != null) {
request.setAttribute("list", list);
request.getRequestDispatcher("product.jsp").forward(request, response);
} else {
response.sendRedirect("main.jsp");
}
} catch (Exception e) {
// TODO: handle exception
}
}
测试
http://localhost:8081/ProductTest/OperatorServlet?op=queryLike&&name=王
4、main.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import="com.l.bean.Product"%>
<%@ page import="java.util.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>在此处插入标题</title>
<script>
function del(data){
decide=confirm("确认删除吗?");
if(decide){
self.location.href="OperatorServlet?op=delete&&id="+data;
}
}
</script>
</head>
<body>
<center>
<table border="1" height="300"width="500" >
<tr>
<th width="50">编号</th>
<th width="50">名称</th>
<th width="50">产地</th>
<th width="50">价格</th>
<th width="80" colspan="2">操作</th>
</tr>
<%
List<Product> list=(List)request.getAttribute("list");
for (Product p : list){
%>
<tr>
<td><%=p.getId()%></td>
<td><%=p.getName() %></td>
<td><%=p.getAddr() %></td>
<td><%=p.getPrice() %></td>
<td><a href="#" onclick="del(<%=p.getId()%>)">删除</a></td>
<td><a href="update.jsp?id=<%=p.getId()%>">更新</a></td>
</tr>
<%
}
%>
</table>
</center>
</body>
</html>
测试