Spring MVC靜態頁面


以下範例顯示如何使用Spring MVC Framework編寫一個簡單的基於Web的應用程式,它可以使用<mvc:resources>標記存取靜態頁面和動態頁面。首先使用Eclipse IDE建立一個動態WEB專案,並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程式:

  1. 建立一個簡單的動態Web專案:StaticPages,並在 src 目錄下建立一個 com.yiibai.springmvc 包。
  2. com.yiibai.springmvc包下建立一個Java類WebController
  3. jsp子檔案夾下建立一個靜態檔案final.html
  4. WebContent/WEB-INF檔案夾下建立一個Spring組態檔案 StaticPages-servlet.xml,如下所述。
  5. 最後一步是建立所有源和組態檔案的內容並執行應用程式,如下所述。

完整的專案檔案結構如下所示 -

WebController.java 的程式碼如下所示 -

package com.yiibai.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WebController {

   @RequestMapping(value = "/index", method = RequestMethod.GET)
   public String index() {
       return "index";
   }

   @RequestMapping(value = "/staticPage", method = RequestMethod.GET)
   public String redirect() {

      return "redirect:/pages/final.html";
   }
}

StaticPages-servlet.xml 的程式碼如下所示 -

<?xml version="1.0" encoding="UTF-8"?>
   <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
          xmlns:context="http://www.springframework.org/schema/context"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

      <context:component-scan base-package="springmvc"/>

      <mvc:resources mapping="/jsp/**" location="/WEB-INF/jsp/"/>
      <mvc:annotation-driven/>


</beans>

這裡使用<mvc:resources ..../>標記來對映靜態頁面。對映屬性必須是指定http請求的URL模式的Ant模式。location屬性必須指定一個或多個有效的資源目錄位置,其中包含靜態頁面,包括圖片,樣式表,JavaScript和其他靜態內容。可以使用逗號分隔的值列表指定多個資源位置。

下面是Spring檢視檔案WEB-INF/jsp/index.jsp的內容。這將是一個登入頁面,此頁面將傳送一個請求存取staticPage服務方法,該方法將此請求重定向到WEB-INF/pages檔案夾中的靜態頁面。

index.jsp 頁面的程式碼如下 -

<%@ page contentType="text/html; charset=UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring Landing Page</title>
</head>
<body>
<h2>Spring Landing Page</h2>
<p>點選下面的按鈕獲得一個簡單的HTML頁面</p>
<form:form method="GET" action="/StaticPages/staticPage">
<table>
    <tr>
    <td>
    <input type="submit" value="獲取HTML頁面"/>
    </td>
    </tr>
</table>  
</form:form>
</body>
</html>

final.html 的完整程式碼如下 -

<html>
<head>
    <title>Spring Static Page</title>
</head>
<body>

<h2>A simple HTML page</h2>

</body>
</html>

完成建立源和組態檔案後,匯出應用程式。右鍵單擊應用程式,並使用匯出> WAR檔案選項,並將檔案儲存為HelloWeb.war 在Tomcat的webapps檔案夾中。

現在啟動Tomcat伺服器,現在嘗試存取URL => http://localhost:8080/HelloWeb/index 。 如果Spring Web應用程式沒有問題,應該看到以下結果:

單擊「獲取HTML頁面」按鈕存取staticPage服務方法中提到的靜態頁面。如果Spring Web應用程式沒有問題,應該看到以下結果: