Java实现搜索功能代码详解

这篇文章主要介绍了Java实现搜索功能代码详解,实现思路小编给大家介绍的非常详细,需要的朋友可以参考下

首先,我们要清楚搜索框中根据关键字进行条件搜索发送的是Get请求,并且是向当前页面发送Get请求

//示例代码 请求路径为当前页面路径 "/product"

当我们要实现多条件搜索功能时,可以将搜索条件封装为一个Map集合,再根据Map集合进行搜索

Controller层代码

@GetMapping("/product") public String list(@RequestParam(required = false,defaultValue = "1",name = "p")Integer pageNo, @RequestParam(required = false,defaultValue = "")String productName, @RequestParam(required = false,defaultValue = "")String place, @RequestParam(required = false,defaultValue = "")Integer typeId, @RequestParam(required = false,defaultValue = "")BigDecimal minPrice, @RequestParam(required = false,defaultValue = "")BigDecimal maxPrice, Model model) { Map searchParam = new HashMap(); searchParam.put("productName",productName); searchParam.put("place",place); searchParam.put("typeId",typeId); searchParam.put("minPrice",minPrice); searchParam.put("maxPrice",maxPrice); PageInfo pageInfo = kaolaService.findByPageNo(pageNo,searchParam); model.addAttribute("pageInfo",pageInfo); return "product/list"; }

业务层代码

public PageInfo findByPageNo(Integer pageNo, Map searchParam) { pageHelper.startPage(pageNo,10); List kaolaList = kaolaMapper.findBySearchParamWithType(searchParam); return new PageInfo(kaolaList); }

MyBatis中的mapper.xml:

SELECT kaola.*, kaola_type.id AS 'kaolaType.id', kaola_type.type_name AS 'kaolaType.typeName', parent_id AS 'kaolaType.parentId' FROM kaola INNER JOIN kaola_type ON kaola.type_id = kaola_type.id kaola.product_name LIKE concat('%',#{productName},'%') and kaola.place = #{place} and kaola.type_id = #{typeId} = #{minPrice} ]]> ORDER BY kaola.id DESC

这样,就可以从前端到后端实现多条件搜索功能了。我们还会遇到这样一种情况,在输入搜索条件时,显示列表会不断自动刷新,这里其实用到了Ajax的相关内容,在输入的过程中,会不断发出Ajax请求,然后刷新页面

value="${param.productName}"是从请求url的参数中获取值,实现在输入关键字搜索后刷新页面显示关键字这一功能,直接上图:

在输入中文关键字进行搜索时,可以使用encodeURIComponent解决url路径显示中文乱码问题:

//分页 $('#pagination-demo').twbsPagination({ totalPages: ${pageInfo.pages}, visiblePages: 10, first:'首页', last:'末页', prev:'上一页', next:'下一页', href:"?productName="+encodeURIComponent('${param.productName}')+"&place="+encodeURIComponent('${param.place}') + "&typeId=${param.typeId}&minPrice=${param.minPrice}&maxPrice=${param.maxPrice}&p={{number}}" });

点击查看大图

搜索结果

总结

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...