ResourceBundleViewResolver
使用屬性檔中定義的視圖bean
來解析視圖名稱。 以下示例顯示如何使用Spring Web MVC框架中的ResourceBundleViewResolver
。
ResourceBundleViewResolver-servlet.xml 配置如下所示 -
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
這裏basename
是指攜帶視圖的資源束的名稱。資源束的默認名稱是views.properties
,可以使用basename
屬性重寫(也就是將views
修改為其他名稱,對應的views.properties
檔案名稱也要修改)。
views.properties 配置如下所示 -
hello.(class)=org.springframework.web.servlet.view.JstlView
hello.url=/WEB-INF/jsp/hello.jsp
例如,使用上面的配置,如果URI
:
- 對於
/hello
請求,DispatcherServlet
會將請求轉發到由views.properties
中定義的hello
對應的hello.jsp
。 - 這裏“
hello
”是要匹配的視圖名稱。class
指定視圖類型,url
是視圖的位置。
首先,讓我們使用Eclipse IDE,並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程式:
- 創建一個名稱為 ResourceBundleViewResolver 的動態WEB專案。
- 在
com.zaixian.springmvc
包下創建一個Java類HelloController
。 - 在
jsp
子檔夾下創建一個視圖檔:hello.jsp
。 - 在
src
檔夾下創建屬性檔views.properties
。 - 下載JSTL庫jstl.jar。 把它放在
CLASSPATH
中。 - 最後一步是創建所有源和配置檔的內容並運行應用程式,詳細如下所述。
完整的專案檔目錄結構如下所示 -
HelloController.java 的代碼如下所示 -
package com.zaixian.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello, Spring MVC資源綁定視圖解析器!");
return "hello";
}
}
ResourceBundleViewResolver-servlet.xml 配置如下所示 -
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.zaixian" />
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
</beans>
views.properties 配置如下所示 -
hello.(class)=org.springframework.web.servlet.view.JstlView
hello.url=/WEB-INF/jsp/hello.jsp
hello.jsp 的代碼如下所示 -
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
完成創建源和配置檔後,發佈應用程式到Tomcat伺服器。
現在啟動Tomcat伺服器,當訪問URL => http://localhost:8080/ResourceBundleViewResolver/hello , 如果Spring Web應用程式沒有問題,應該看到以下結果:
上一篇:
Spring MVC Xml視圖解析器
下一篇:
Spring MVC多解析器映射