具体说明参看:http://www.cnblogs.com/Leo_wl/p/4456882.html
controller代码:
@ResponseBody
@RequestMapping("ajaxUserCode")
public Map ajaxUserCode(HttpServletRequest req){
String keyword=req.getParameter("keyword");
//===============模糊查询
Map paraMap=new HashMap();
paraMap.put("username", keyword);
ListresultList=null;
try {
Map resultMap=userSrv.queryUser(paraMap);
resultList=(List)resultMap.get("list");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//===============模糊查询
Map map=new HashMap();
ListjsonList=new ArrayList();
if(resultList!=null && !resultList.isEmpty()){
for(Map temp:resultList){
String name=(String)temp.get("name");
Map newMap=new HashMap();
newMap.put("title", name);
jsonList.add(newMap);
}
}else{
Map newMap=new HashMap();
newMap.put("title", "");//如果查询不到,就返回空值。否则提示会出错
jsonList.add(newMap);
}
map.put("data", jsonList.toArray());
return map;
}service代码:
public Map queryUser(Map map) throws Exception{
String username=(String)map.get("username");
// String age=(String)map.get("age");
String xb=(String)map.get("xb");
Map paraMap=new HashMap();
paraMap.put("username", username);
paraMap.put("xb", xb);
List list=dao.findList("userMapper.queryUserWhere", paraMap);
Map resutMap=new HashMap();
resutMap.put("list", list);
return resutMap;
}mapper.xml中的sql
<select id="queryUserWhere" parameterType="map" resultType="map">
select id,username as name,password as pwd from user
<where>
<if test="username!=null and uername!=''">
and username like #{username}"%"
</if>
<if test="xb!=null and xb!=''">
and xb=#{xb}
</if>
</where>
</select>返回的json数据格式为:
{
"data": [
{
"title": "张三"
},
{
"title": "李四"
},
{
"title": "王五"
},
{
"title": "tom"
},
{
"title": "jerry"
},
{
"title": "mym"
}
]
}