如何实现模糊查询结果

分析:

因为模糊查询的条件比较不定性,所以可以定义一个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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值