Java实现搜索功能代码详解实现搜索功能代码详解
主要介绍了Java实现搜索功能代码详解,实现思路小编给大家介绍的非常详细,需要的朋友可以参考下
首先,我们要清楚搜索框中根据关键字进行条件搜索发送的是Get请求,并且是向当前页面发送Get请求
//示例代码 请求路径为当前页面路径 "/product"
<!-- 搜索框 get请求 根据商品名称的关键字进行搜索-->
<form action="/product" class="form-inline pull-left" >
<input type="text" name="productName" placeholder="商品名称" class="form-control" value="${param.productName}">
<button class="btn btn-primary"><i class="fa fa-search"></i></button>
</form>
当我们要实现多条件搜索功能时,可以将搜索条件封装为一个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<String,Object> searchParam = new HashMap<>();
searchParam.put("productName",productName);
searchParam.put("place",place);
searchParam.put("typeId",typeId);
searchParam.put("minPrice",minPrice);
searchParam.put("maxPrice",maxPrice);
PageInfo<Kaola> pageInfo = kaolaService.findByPageNo(pageNo,searchParam);
model.addAttribute("pageInfo",pageInfo);
return "product/list";
}
业务层代码:
public PageInfo<Kaola> findByPageNo(Integer pageNo, Map<String, Object> searchParam) {
PageHelper.startPage(pageNo,10);
List<Kaola> kaolaList = kaolaMapper.findBySearchParamWithType(searchParam);
return new PageInfo<>(kaolaList);
}
MyBatis中的mapper.xml:
<select id="findBySearchParamWithType" resultType="com.kaishengit.entity.Kaola">
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
<where>
<if test="productName != null and productName != ''">
kaola.product_name LIKE concat('%',#{productName},'%')
</if>
<if test="place != null and place != ''">
and kaola.place = #{place}
</if>
<if test="typeId != null and typeId != ''">
and kaola.type_id = #{typeId}
</if>
<if test="minPrice !=null and minPrice != ''">
<![CDATA[ and kaola.price >= #{minPrice} ]]>
</if>
<if test="maxPrice !=null and maxPrice != ''">
<![CDATA[ and kaola.price <= #{maxPrice} ]]>
</if>
</where>
ORDER BY kaola.id DESC
</select>
评论0