Spring MVC - 資源繫結檢視解析器示例



ResourceBundleViewResolver 用於使用屬性檔案中定義的檢視 Bean 解析檢視名稱。以下示例演示瞭如何在 Spring Web MVC 框架中使用 ResourceBundleViewResolver。

TestWeb-servlet.xml

<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
   <property name = "basename" value = "views" />
</bean>

這裡,basename 指的是資源繫結的名稱,它包含檢視。資源繫結的預設名稱為views.properties,可以透過 basename 屬性覆蓋。

views.properties

hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url = /WEB-INF/jsp/hello.jsp

例如,使用上述配置,如果請求 URI -

  • /hello,DispatcherServlet 將請求轉發到 views.properties 中 bean hello 定義的 hello.jsp。

  • 這裡,“hello” 是要匹配的檢視名稱。而class 指的是檢視型別,URL 是檢視的位置。

首先,讓我們準備好一個可用的 Eclipse IDE,並考慮以下步驟來使用 Spring Web 框架開發基於動態表單的 Web 應用程式。

步驟 描述
1 在 Spring MVC - Hello World 章節中說明的基礎上,建立一個名為 TestWeb 的專案,放在 com.tutorialspoint 包下。
2 在 com.tutorialspoint 包下建立一個名為 HelloController 的 Java 類。
3 在 jsp 子資料夾下建立一個名為 hello.jsp 的檢視檔案。
4 在 src 資料夾下建立一個名為 views.properties 的屬性檔案。
5 下載 JSTL 庫 jstl.jar。將其放入你的 CLASSPATH 中。
6 最後一步是建立原始檔和配置檔案的內容,並匯出應用程式,如下所述。

HelloController.java

package com.tutorialspoint;

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";
   }

}

TestWeb-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.tutorialspoint" />

   <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>

建立完原始檔和配置檔案後,匯出你的應用程式。右鍵單擊你的應用程式,使用匯出 → WAR 檔案選項,並將你的 HelloWeb.war 檔案儲存到 Tomcat 的 webapps 資料夾中。

現在,啟動你的 Tomcat 伺服器,並確保你可以使用標準瀏覽器從 webapps 資料夾訪問其他網頁。嘗試訪問 URL - https://:8080/HelloWeb/hello,如果 Spring Web 應用程式一切正常,我們將看到以下螢幕。

Spring Internal Resource View Resolver
廣告

© . All rights reserved.