欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

查询和模糊查询

程序员文章站 2022-06-07 15:54:28
...
1.查询操作
query.do->doPost->query方法->JSP
query方法的代码:
private void query(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		//1.调用CustomerDAO的getAll()得到Customer的集合
		List<Customer> customers=customerDAO.getAll();
		//2.把 Customer的集合放入request中
		request.setAttribute("customers", customers);
		
		//3.转发页面到index.jsp(不能是重定向)
		request.getRequestDispatcher("/index.jsp").forward(request, response);
}	
JSP:核心
获取request中的customers属性,遍历显示。
<%
	List<Customer> customers=(List<Customer>)request.getAttribute("customers");
	for(Customer customer:customers){
%>
	<tr>
		<td><%= customer.getId() %></td>
		<td><%= customer.getName() %></td>
		<td><%= customer.getAddress() %></td>
		<td><%= customer.getPhone() %></td>
		<td>
			<a href="">Update</a>
			<a href="delete.do?id=<%=customer.getId() %>" class="delete">Delete</a>
		</td>
	</tr>
<%		
	}
%>
2.模糊查询:
SQL:
public List<Customer> getForListWithCriteriaCustomer(CriterCustomer cc) {
	
		String sql="select id,name,address,phone from customers where "+"name like ? and address like ? and phone like ?";
		return getForList(sql,cc.getName(),cc.getAddress(),cc.getPhone());
	}
为了正确的填充占位符时,重写了CriteriaCustomer的getter:
public String getName() {
		if (name==null) 
			name="%%";
		else
			name="%"+name+"%"; 
		return name;
}
public String getAddress() {
		if (address==null) 
			address="%%";
		else
			address="%"+address+"%"; 
		return address;
}
修改Servlet:获取请求参数;把请求参数封装为CriteriaCustomer对象,在调用
public List<Customer> getForListWithCriteriaCustomer(CriterCustomer cc);方法
相关标签: 查询 模糊查询