},
methods:{
loadData(){
//发送数据到后台
ly.http.post(“/search/page”,this.search).then(resp => {
console.log(resp);
}).catch(error =>{
})
}
},
3)刷新页面观察请求发送情况
请求路径
请求参数
发送请求成功
2、后台接收请求并返回数据
(1)编写对象用于接收页面发送的请求
package com.leyou.search.pojo;
public class SearchRequest {
private String key;//搜索字段
private Integer page;//当前页
private static final Integer DEFAULT_SIZE = 20;//每页个数
private static final Integer DEFAULT_PAGE = 1;//默认页
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Integer getPage() {
if(page == null){
return DEFAULT_PAGE;
}
//获取页码的时候进行校验,不能小于1
return Math.max(DEFAULT_PAGE,page);// Math.max返回DEFAULT_PAGE,page之间的最大值
}
public void setPage(Integer page) {
this.page = page;
}
public static Integer getDefaultSize() {
return DEFAULT_SIZE;
}
}
(2)SearchController
首先分析几个问题:
-
请求方式:
Post
-
请求路径:
/search/page
,不过前面的/search应该是网关的映射路径,因此真实映射路径page,代表分页查询。 -
请求参数:
json
格式,目前只有一个属性: key,搜索关键字,但是搜索结果页一定是带有分页查询的,所以将
来肯定会有page属性,因此我们可以用一个对象来接收请求的json数据:
- 返回值为之前定义的PageResult
package com.leyou.search.web;
import com.leyou.common.vo.PageResult;
import com.leyou.search.pojo.Goods;
import com.leyou.search.pojo.SearchRequest;
import com.leyou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SearchController {
@Autowired
private SearchService searchService;
/*
搜索功能
*/
@PostMapping(“page”)
public ResponseEntity<PageResult> search(@RequestBody SearchRequest request){
return ResponseEntity.ok(searchService.search(request));
}
}
(3)完善SearchService(设置将请求的字段进行)
public PageResult search(SearchRequest request) {
Integer page = request.getPage();
Integer size = request.getSize();
//创建查询构建器SpringDataElasticSearch - NativeSearchQueryBuilder过滤聚合高亮查询
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//0 结果过滤
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{“id”,“subTitle”,“skus”},null));
//1 分页
queryBuilder.withPageable(PageRequest.of(page,size));
//2 过滤
queryBuilder.withQuery(QueryBuilders.matchQuery(“all”,request.getKey()));
//3 查询
Page result = repository.search(queryBuilder.build());
//4 解析结果
long total = result.getTotalElements();
int totalPage = result.getTotalPages();
List goodsList = result.getContent();
return new PageResult<>(total,totalPage,goodsList);
}
(4)从新启动运行测试
http://www.leyou.com/search.html?key=手机
(4)上述当中我们发现其他字段都为null(设置jackson如果是null就不返回数据)
jackson:
default-property-inclusion: non_null
重新运行并测试
刷新刚刚的网页
返回完美的数据
测试翻页
(5)商户数情况下发现永远查询不到第一页所有需要修改代码(SearchService)
Integer page = request.getPage() - 1;
重新运行并测试
1、将返回的数据渲染到页面上
(1)找到页面上的 <div class="goods-list">
删除其他的li,设置v-for
</