我有一个Controller类,其中包含许多接收或从JSP页面向或发送数据的方法。所有这些方法都能正常工作但是当我尝试以相同的方法接收数据和打印数据时,我尝试返回的页面将无法打开
例如,当从前端调用commuteChecker
时,此方法将成功将对象的ArrayList打印到/commuteCheckerPage
JSP页面:
@RequestMapping(value = "/commuteCheckerPage", method = RequestMethod.GET)
public String commuteChecker(@Valid Commutes commutes, BindingResult bindingResult, Model model) {
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String username = loggedInUser.getName(); // Authentication for
commutesRepository.save(commutes);
User user = userRepository.findByUsername(username);
List<Commutes> savedCommutes = user.getSavedCommutes();
for (int i = 0; i < savedCommutes.size(); i++) {
model.addAttribute("savedCommutes", savedCommutes);
}
return "commuteChecker";
}
同样,当从前端调用/skip
时,welcome
页面会成功返回/打开。
@RequestMapping(value = "/skip", method = RequestMethod.GET)
public String Skip() {
return "welcome";
}
似乎当我包含@RequestParam
来接收数据然后尝试添加model.addAttribute
以将此数据打印到页面时,该方法中的代码将起作用( print debug打印正确的值)但houseprice
JSP页面将无法打开。在下面的示例中,我获取latitude
和longitude
值,查询数据库并根据latitude
周围的半径计算平均房价和查询中的房屋数量提供了longitude
个值。
@RequestMapping(value = "/parseHousePrice", method={RequestMethod.POST, RequestMethod.GET})
public @ResponseBody String parseHousePrice(HousePrice housePrice,
@RequestParam("latitude") double latitude,
@RequestParam("longitude") double longitude,
Model model) {
// Running method that queries PostgreSQL for average price
double housePriceAverage = parseHousePrice.ParseHousePrice(latitude, longitude);
// Adding results from PostgreSQL db to array to get number of houses
List<Double> housePriceList = parseHousePrice.getList();
int housePriceListSize = housePriceList.size();
// Simple println debugger
System.out.println("The average house price for this area is: " + housePriceAverage + " based on " + housePriceListSize + " property prices in this area");
// Im trying to pass the two values calculated above to houseprice.jsp
model.addAttribute("houseprice", housePriceAverage);
model.addAttribute("housepricelistsize", housePriceListSize);
// Page I'm trying to load but wont open
return "houseprice";
}
但正如我先前所说,该页面根本无法打开。我已尝试了多种不同的方法来实现这一点,即ModelAndView
和HttpSession
,而不是使用Model
,也不会加载页面,这让我相信我不能在同一控制器方法中接收和发送数据。这是正确的,如果有的话有办法解决这个问题吗?
答案 0 :(得分:0)
问题出在这里
public @ResponseBody String parseHousePrice(HousePrice housePrice,
@RequestParam("latitude") double latitude,
@RequestParam("longitude") double longitude,
Model model)...
应该是这样的
public String parseHousePrice(HousePrice housePrice,
@RequestParam("latitude") double latitude,
@RequestParam("longitude") double longitude,
Model model)...
删除使控制器写入响应主体而不是返回视图的 @ResponseBody