如何实现模糊查询结果

分析:

因为模糊查询的条件比较不定性,所以可以定义一个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中,跳转到前端页面进行显示

前端页面的写法:





      姓名:
       性别:checked="checked"/> 男
    checked="checked"/> 女

    
     
      地址:
     电话:
     
    
 
 

你可能感兴趣的:(mvc)