廢話少說,給你們看代碼:
//provide的controller
@ResponseBody
@RequestMapping(value = "details",method = RequestMethod.GET)
public PageInfo<Detail> queryByTitle(@RequestParam(required = false) String title, @RequestParam(required = false) Integer pageNum,@RequestParam(required = false) Integer pageSize){
System.out.println("title:"+title+",pageNum:"+pageNum+",pageSize:"+pageSize);
if (pageNum == null) {
pageNum=1;
}
if (pageSize == null) {
pageSize=2;
}
PageInfo<Detail> pageInfo = detailService.queryByTitle(title, pageNum, pageSize);
return pageInfo;
}
記得加@ResponseBody注解,不然會consumer的請求會報org.springframework.web.client.HttpClientErrorException$NotFound: 404 null。
//負責調用provider的方法,獲取數據
@Autowired
private RestTemplate restTemplate;
//在provider端資源的路徑
private String url="http://localhost:8080/details";
//導游provider的方法查詢所有用戶
public PageInfo<Detail> queryByTitle(String title,Integer pageNum,Integer pageSize){
Map<String, Object> params = new HashMap<>();
params.put("pageSize", pageSize);
params.put("pageNum", pageNum);
params.put("title", title);
//使用占位符,map中不能沒有占位符的鍵值對
PageInfo pageInfo = restTemplate.getForObject(url + "?pageSize={pageSize}&pageNum={pageNum}&title={title}", PageInfo.class, params);
//集合轉json再轉回來
String json = JSON.toJSONString(pageInfo.getList());
List<Detail> details = JSON.parseArray(json, Detail.class);
pageInfo.setList(details);
return pageInfo;
}
集合轉json再轉回來,這一步是個大坑啊,說起來都是淚,直接返回pageInfo,前台Thymeleaf頁面也可以遍歷出集合並拿到值進行展示,但怪就怪在,我Timestamp的日期不能進行格式化(<td th:text="${#dates.format(detail.createdate, 'yyyy-MM-dd HH:mm')}"></td>),我不進行格式化日期,頁面可以輸出,說明我的日期不是空的。但是日期不格式化也不行,報錯EL1029E: A problem occurred when trying to execute method 'format' on object和Failed to convert from type [java.lang.String] to type [java.util.Date]什么的。百度中。。。 考慮是不是格式化方法不行 ,試了各種格式化方式發現還是不行,說我日期是String類型的,我尋思着擱后台遍歷打印一下看看日期是不是Timestamp類型的,不遍歷沒啥,一遍歷報錯!java.util.LinkedHashMap cannot be cast to com.zhou.entity.Detail,說不能轉換成我的Detail實體類 ??? ,百度。。。 (https://blog.csdn.net/shijiujiu33/article/details/93410585)返回的時候會把PageInfo轉變成json的形式(內部是jackjson技術支持的)
所以遍歷集合就會報上面的異常(具體情況也不太清楚)。根據這篇博客,試了一下,發現可以遍歷了,而且頁面也可以格式化日期了。深坑!!!。
如果是返回對象集合的話建議這樣做:
@Autowired
private RestTemplate restTemplate;
//在provider端資源的路徑
private String url="http://localhost:8080/comments";
//根據新聞編號查詢所有評論
public List<Comment> queryByNewsId(Integer id){
Comment[] comment = restTemplate.getForObject(url + "/" + id, Comment[].class);
return Arrays.asList(comment);
}
返回對象數組,再將其轉為對象集合。就不會出現上面的情況,但我是直接返回PageInfo,第一次用RestTemplate,如有大佬,還望指點一下。
