我正在使用Spring开发REST Web服务。下面的第一个代码是我的Web服务的方法,它返回用户列表。第二个代码是我的Spring REST Template客户端从该Web服务方法获取响应。
获取用户列表的Web服务方法:
@RequestMapping(value = "/allusers", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getAllUsers() {
List<UserDetails> users = userServices.getAllUsers();
HttpHeaders header = new HttpHeaders();
header.setExpires(600);
HttpEntity<List<UserDetails>> httpEntity = new HttpEntity<>(users, header);
HttpStatus httpStatus;
if(users != null){
httpStatus = HttpStatus.OK;
} else {
httpStatus = HttpStatus.NOT_FOUND;
}
return new ResponseEntity<>(httpEntity, httpStatus);
}
REST客户端
@RequestMapping("/list_all_users")
public ModelAndView goAllUsers() {
ModelAndView mv = new ModelAndView("allusersdisplay");
String url = "http://localhost:8080/SpringRestAddrs/services/allusers";
RestTemplate rTemplate = new RestTemplate();
*List<String> users = (List)rTemplate.getForObject(url, HttpEntity.class).getBody();*
mv.addObject("users", users);
return mv;
}
由于ClassCastException
对象的主体包含HttpEntity
类型的对象列表,而UserDetails
List
,我希望该行周围的String
被星号(*)包围左侧定义的是ratingnumber
类型的对象列表。这里真的发生了什么?
答案 0 :(得分:0)
在此示例中,您只是将其强制转换为通用列表。投射到bin\File.extension
会给你“所需”的错误。
List<String>
答案 1 :(得分:0)
您正在获取此行为,因为您正在转换为List。
JVM执行
List<String> users = (List)rTemplate.getForObject(url, HttpEntity.class).getBody();
JVM仅将users变量指向该内存空间。如果要获取 ClassCastException ,则必须使用List的任何值。例如:
System.out.println(users.get(0));