首先需要配置下SpringMVC默認(rèn)視圖衅鹿,這里配置的是jsp
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
渲染jsp模板
如下代碼所示冗锁,直接return Jsp模板的路徑(不包括后綴)即可。將需要在頁面讀取的數(shù)據(jù)通過model.addAttribute
贷腕,在jsp頁面直接可以el獲取設(shè)置的變量
@RequestMapping(value="html", method=RequestMethod.GET)
public String prepare(Model model) {
model.addAttribute("foo", "bar");
model.addAttribute("fruit", "apple");
return "views/html";
}
jsp代碼如下所示:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>My HTML View</title>
<link href="<c:url value="/resources/form.css" />" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="success">
<h3>foo: "${foo}"</h3>
<h3>fruit: "${fruit}"</h3>
</div>
</body>
</html>
默認(rèn)請求路徑作為模板名
如果Controller的方法返回void阔蛉,則SpringMVC會將請求路徑直接作為模板的路徑,如下所示臊诊,下面會映射到viewName.jsp上。
@RequestMapping(value="/viewName", method=RequestMethod.GET)
public void usingRequestToViewNameTranslator(Model model) {
model.addAttribute("foo", "bar");
model.addAttribute("fruit", "apple");
}
使用路徑變量
使用@PathVariable
可以讀取url中傳遞的參數(shù)斜脂,SpringMVC會將方法中的參數(shù)合并到Model上去抓艳,這里不用顯示的往Model里設(shè)置屬性,在jsp可以直接用EL讀取
@RequestMapping(value="pathVariables/{foo}/{fruit}", method=RequestMethod.GET)
public String pathVars(@PathVariable String foo, @PathVariable String fruit) {
// No need to add @PathVariables "foo" and "fruit" to the model
// They will be merged in the model before rendering
return "views/html";
}
數(shù)據(jù)綁定
如下代碼所示帚戳,可以將url中的變量直接綁定到j(luò)avabean上
@RequestMapping(value="dataBinding/{foo}/{fruit}", method=RequestMethod.GET)
public String dataBinding(@Valid JavaBean javaBean, Model model) {
// JavaBean "foo" and "fruit" properties populated from URI variables
return "views/dataBinding";
}