XmlViewResolver
用於在xml
檔中定義的視圖bean
來解析視圖名稱。以下示例演示如何在Spring Web MVC框架使用XmlViewResolver
。
XmlViewResolver-servlet.xml 配置如下所示 -
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
views.xml 配置如下所示 -
<bean id="hello"
class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/jsp/hello.jsp" />
</bean>
例如,使用上面的配置,如果URI
:
- 對於
/hello
請求,DispatcherServlet
會將請求轉發到由view.xml
中定義的hello
對應的hello.jsp
。
首先,讓我們使用Eclipse IDE,並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程式:
- 創建一個名稱為 XmlViewResolver 的動態WEB專案。
- 在
com.zaixian.springmvc
包下創建一個Java類HelloController
。 - 在
jsp
子檔夾下創建一個視圖檔:hello.jsp
。 - 下載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 Framework!");
return "hello";
}
}
XmlViewResolver-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.springmvc" />
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml 配置如下所示 -
<bean id="hello"
class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/jsp/hello.jsp" />
</bean>
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/XmlViewResolver/hello , 如果Spring Web應用程式沒有問題,應該看到以下結果:
上一篇:
Spring MVC內部資源視圖解析器
下一篇:
Spring MVC資源綁定視圖解析器