![](/img/trans.png)
[英]How to pass values from Spring Controller to jsp page?( the passed values is to be used to intialise javascript variables in jsp page
[英]How do I pass a value from a controller to a JSP page in Spring?
我正在嘗試將數據從Controller傳遞到JSP頁面,但是遇到了一些問題。 Controller中有一種方法,可以根據用戶提供的經度和緯度值查詢房價信息數據庫。 調試顯示在打印數據庫houseprice
值和結果中的houses
數到Eclipe的控制台時,數據庫查詢正確,但是我無法加載JSP頁面,因此無法將其打印到JSP頁面。
@RequestMapping(value = "/parseHousePrice", method={RequestMethod.POST, RequestMethod.GET})
public @ResponseBody String parseHousePrice(@RequestBody HousePrice housePriceObject,
@RequestParam("latitude") double latitude,
@RequestParam("longitude") double longitude,
Model model) {
double housePriceAverage = parseHousePrice.ParseHousePrice(latitude, longitude);
// This passes the lat & long into a method that will query the database
List<Double> housePriceList = parseHousePrice.getList();
// This will return the number of houses that were queried
int housePriceListSize = housePriceList.size();
// This print statement successfully prints the results fromt he query
System.out.println("The average house price for this area is: " + housePriceAverage + " based on " + housePriceListSize + " property prices in this area");
model.addAttribute("houseprice", housePriceAverage);
model.addAttribute("housepricelistsize", housePriceListSize);
// JSP Page I'm trying to pass the information above to
return "houseprice";
}
數據是通過一個JSP上的Javascript函數中的AJAX請求發送的,而我正嘗試使用來自控制器的信息打開一個新的JSP頁面
function parseHousePrice(){
// Calculates users latitude and longitude
$('.search_latitude').val(marker.getPosition().lat());
var Lat = marker.getPosition().lat();
console.log(Lat);
$('.search_longitude').val(marker.getPosition().lng());
var Long = marker.getPosition().lng();
console.log(Long);
$.ajax({
type: "POST",
url: "/parseHousePrice",
data: { latitude: Lat,
longitude: Long,
},
datatype: 'json'
});
}
我從導航欄中的鏈接中這樣稱呼它:
<li><a href= "javascript:parseHousePrice();" >House Price</a></li>
在JSP頁面中,我嘗試了幾種方法來收集上面計算的信息並顯示出來。 一種方法是使用百里香,但這不會打印
<h4>Average House Price <text th:text="${houseprice}" /> </h4>
<h4>Number of Houses the average is caluclated by: <text th:text="${housepricelistsize}" /> </h4>
另一種方法是放下胸腺葉並這樣稱呼它:
<h1>${houseprice} </h1>
<h1>${housepricelistsize} </h1>
但是,沒有運氣。 我可以將信息成功傳遞到控制器並打印到控制台,但是我遇到了麻煩,將其從控制器傳遞到JSP頁面。 任何幫助,將不勝感激!
據我了解,當您單擊導航欄時,您正在嘗試使用房價和大小更新jsp頁面。 我試圖根據我的理解回答這個問題。
在您的jsp中,我會輸入以下內容:
<h1 id ="housepriceID"></h1>
<h1 id ="housepricesize"> </h1>
現在在您的jQuery上,
$.ajax({
type: "POST",
url: "/parseHousePrice",
data: { latitude: Lat,
longitude: Long,
},
datatype: 'json'
})
.done(function( data, textStatus, jqxhr ) {
$("#housepriceID").val(data.houseprice);
$("#housepricesize").val(data.housepricelistsize);
});
這應該可以解決您的問題。
如果我沒看錯,代碼model.addAttribute
應該是model.setAttribute
,因為您要將從數據庫查詢的數據添加到會話中,因此必須改用.setAttribute
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.