分析:
因为模糊查询的条件比较不定性,所以可以定义一个Map集合来进行接收模糊查询的条件
select t.*,rownum n from t_address t where 1=1;
select t.*,rownum n from t_address t where 1=1 and t.userName like ‘%xxx%’;
select t.*,rownum n from t_address t where 1=1 and t.address like ‘%address%’;
select t.*,rownum n from t_address t where 1=1 and t.tel like ‘%tel%’;
select t.*,rownum n from t_address t where 1=1 and t.sex =’xxx’;
步骤
1.提供一个可以模糊查询结果的方法
例如:
public List seachList(Map filter);
注意sql语句应写成:
{
String sql=”select t.*,rownum n from t_address t where 1=1”;
if(filter.get(“userName”)!=null){
sql+=” and t.userName like ‘%”+filter.get(“userName”)+”%’”;
}
if(filter.get(“address”)!=null){
sql+=” and t.address like ‘%”+filter.get(“address”)+”%’”;
}
if(filter.get(“tel”)!=null){
sql+=” and t.tel like ‘%”+filter.get(“tel”)+”%’”;
}
if(filter.get(“sex”)!=null){
sql+=” and t.sex=’”+filter.get(“sex”)+”’”;
}
}
2.获取前端页面传来的模糊查询的条件
String userName=request.getParameter("userName");
String sex=request.getParameter("sex");
String address=request.getParameter("address");
String tel=request.getParameter("tel");
实例化Map类new出一个Map对象filter对象,并将模糊查询的条件塞进map键值对集合中
Map filter=new HashMap();
if(userName!=null&&!"".equals(userName)){
filter.put("userName", userName);
}
if(sex!=null&&!"".equals(sex)){
filter.put("sex", sex);
}
if(address!=null&&!"".equals(address)){
filter.put("address", address);
}
if(tel!=null&&!"".equals(tel)){
filter.put("tel", tel);
}
3.调用public List seachList(filter new出一个Map对象filter )模糊查询方法,将得到的集合对象 List
存进requese.setAttribute中,跳转到前端页面进行显示
前端页面的写法:
|
姓名:<input type="text" name="userName" value="${filter['userName']}"/>
性别:<input type="radio" name="sex" value="男"
<c:if test="${filter['sex']=='男'}">checked="checked"</c:if>/> 男
<input type="radio" name="sex" value="女"
<c:if test="${filter['sex']=='女'}">checked="checked"</c:if>/> 女
</td></tr>
<tr><td>
地址:<input type="text" name="address" value="${filter['address']}"/>
电话:<input type="text" name="tel" value="${filter['tel']}"/>
<input type="submit" value=" 搜索 "/>
</td></tr>
</table>
</form>