這裏是我碰到的一個辦法blog post:
我不想使用這些框架,所以在這一部分我使用jQuery發送AJAX請求到服務器,等待響應並部分更新視圖(片段呈現)。
表單
<form>
<span class="subtitle">Guest list form</span>
<div class="listBlock">
<div class="search-block">
<input type="text" id="searchSurname" name="searchSurname"/>
<br />
<label for="searchSurname" th:text="#{search.label}">Search label:</label>
<button id="searchButton" name="searchButton" onclick="retrieveGuests()" type="button"
th:text="#{search.button}">Search button</button>
</div>
<!-- Results block -->
<div id="resultsBlock">
</div>
</div>
</form>
這種形式包含了將要發送到服務器的搜索字符串(searchSurname)輸入文本。還有一個區域(resultsBlock div),它將使用從服務器收到的響應進行更新。
當用戶單擊按鈕時,retrieveGuests()函數將被調用。
function retrieveGuests() {
var url = '/th-spring-integration/spring/guests';
if ($('#searchSurname').val() != '') {
url = url + '/' + $('#searchSurname').val();
}
$("#resultsBlock").load(url);
}
jQuery的負載功能使得在指定的URL到所述服務器的請求,並把返回的HTML到指定的元素(resultsBlock DIV)。
如果用戶輸入搜索字符串,它將搜索具有指定姓氏的所有客人。否則,它將返回完整的訪客列表。這兩個請求將達到以下要求控制器的映射:
@RequestMapping(value = "/guests/{surname}", method = RequestMethod.GET)
public String showGuestList(Model model, @PathVariable("surname") String surname) {
model.addAttribute("guests", hotelService.getGuestsList(surname));
return "results :: resultsList";
}
@RequestMapping(value = "/guests", method = RequestMethod.GET)
public String showGuestList(Model model) {
model.addAttribute("guests", hotelService.getGuestsList());
return "results :: resultsList";
}
由於彈簧與Thymeleaf集成,它現在將能夠返回的HTML片段。在上面的示例中,返回字符串「results :: resultsList」指向位於結果頁面中的名爲resultsList的片段。讓我們來看看這個結果頁面:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
</head>
<body>
<div th:fragment="resultsList" th:unless="${#lists.isEmpty(guests)}" id="results-block">
<table>
<thead>
<tr>
<th th:text="#{results.guest.id}">Id</th>
<th th:text="#{results.guest.surname}">Surname</th>
<th th:text="#{results.guest.name}">Name</th>
<th th:text="#{results.guest.country}">Country</th>
</tr>
</thead>
<tbody>
<tr th:each="guest : ${guests}">
<td th:text="${guest.id}">id</td>
<td th:text="${guest.surname}">surname</td>
<td th:text="${guest.name}">name</td>
<td th:text="${guest.country}">country</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
的片段,這是註冊客人表,將在結果塊插入。
它是否會刷新頁面? – kamaci
取決於你打電話的方式。如果它的ajax調用頁面不會刷新,否則它會。 –
我真的很喜歡這個。我試圖返回視圖名稱的方法,它也可以。像這樣:'public String getFeeds(){return「feeds :: resultsList」; }' –