从list里筛选从而实现模糊查询

开发工具与关键技术:MyEclipse 10、java
作者:梁添荣
撰写时间:2019-07-18

除了可以写sql语句实现模糊查询,我们还可以从list里筛选出所需要的数据进而实现模糊查询,具体思路:
例:1.这是查询所有数据:List<Pw_outboundcheck> lists=iOutService.select();
2.当jsp进行模糊查询时,例:table1.search({x:x});
3.可在servlet接受x判断是否为null,是则查询全部数据,否则是条件查询,
在new一个list,遍历查询全部数据的list,当list的对象包含x,则满足条件,则添加到新的list里,不满足则不添加,然后再输出新的list
代码如下:
//查询
	private void car(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/json");
		response.setCharacterEncoding("utf-8");
		//车辆
		String curPageStr=request.getParameter("curPage");
		String pageSizeStr=request.getParameter("pageSize");
		int curPage=1;
		int pageSize=7;
		if(curPageStr!=null && Tools.isNum(curPageStr)){
			curPage=Integer.parseInt(curPageStr);
		}
		if(pageSizeStr!=null && Tools.isNum(pageSizeStr)){
			pageSize=Integer.parseInt(pageSizeStr);
		}
		List<Car> lists2=service.select();
		int count=service.sum();
		PrintWriter writer=response.getWriter();
		
		//模糊查询
		String name2=request.getParameter("name2");
		if(name2!=null){
			List<Car> lists3=new ArrayList<Car>();
			for (Car car : lists2) {
				if(car.getCarname().contains(name2)){
					lists3.add(car);
				}
			}
			if(lists3.size()!=0){//因为ToJsonUtil的缺陷,所有list为没有日期会报错
				writer.write(ToJsonUtil.toJson(curPage, lists3.size(), lists3, true));
			}else{
				writer.write(ToJsonUtil.toJson(curPage, 0, lists2, true));
			}
			
		}else{
			writer.write(ToJsonUtil.toJson(curPage, count, lists2, true));
		}
		writer.flush();
		writer.close();

猜你喜欢

转载自blog.csdn.net/weixin_44619313/article/details/96424748