首先,Spring MVC非常灵活。您可以拥有返回由视图引擎生成的 HTML 的后端处理程序,也可以拥有返回 JSON/XML/ProtocolBuffers/等的处理程序。并使用 Mustache 等客户端渲染引擎在浏览器中显示页面,或者您可以将两者结合在同一个应用程序中。
如果您想在服务器上生成 HTML,Spring MVC 允许您使用不同的模板引擎来完成此操作。您可以使用 JSP、Freemarker、Velocity 等。为此,它使用 ViewResolver 抽象,并且在您的代码中您只需处理 ModelAndView API。
有关 ViewResolver 的更多详细信息可以在这里找到:http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html
根据您的问题,听起来您有一个使用 JSP 创建 html 服务器端的后端。为了仅更新表而不是在用户单击刷新按钮时重新加载整个页面,您可以使用一个仅返回 html 表的处理程序,如下所示:
@RequestMapping("/table")
public ModelAndView renderTable() {
List<People> people = peopleService.findAllPeople();
return new ModelAndView("/people", "people", people);
}
我还假设您有另一个处理程序,它返回通过 ajax 嵌入表格的主页。
<body>
...
/* Content of div will be populated via ajax*/
<div id="myTableContainer" />
...
</body>
这个的 JavaScript 应该是这样的:
$(function() {
var myTableContainer = $("#myTableContainer");
var renderTable = function(container) {
$.get("/table", function(data) {
container.empty().html(data);
}
};
/* This is called on document ready */
renderTable(myTableContainer);
/* Use the same renderTable function when the refresh button is clicked */
$("#refreshButton").click(function() {
renderTable(myTableContainer);
});
}