以下示例顯示如何使用Spring MVC Framework編寫一個簡單的基於Web的應用程式,它可以使用<mvc:resources>
標記訪問靜態頁面和動態頁面。首先使用Eclipse IDE創建一個動態WEB專案,並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程式:
- 創建一個簡單的動態Web專案:StaticPages,並在
src
目錄下創建一個com.zaixian.springmvc
包。 - 在
com.zaixian.springmvc
包下創建一個Java類WebController
。 - 在
jsp
子檔夾下創建一個靜態檔final.html
。 - 在
WebContent/WEB-INF
檔夾下創建一個Spring配置檔StaticPages-servlet.xml
,如下所述。 - 最後一步是創建所有源和配置檔的內容並運行應用程式,如下所述。
完整的專案檔結構如下所示 -
WebController.java 的代碼如下所示 -
package com.zaixian.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應用程式沒有問題,應該看到以下結果: