Spring 是全棧輕量級 J2EE 框架,核心特點:模組化(按需使用)、非侵入式(POJO 開發)、整合現有技術(Hibernate、Logging 等)而非重造輪子。常見組合:JSTL + Struts/WebWork + Spring + Hibernate。
Spring 提供精簡實用的標籤庫,非大而全,作為其他視圖技術的補充:
spring:hasBindErrors —— 顯示綁定錯誤spring:bind —— 表單字段綁定spring:transform —— 數據轉換顯示spring:message —— 國際化消息spring:htmlEscape —— HTML 轉義spring:theme —— 主題支持對應 BindErrorsTag。檢查指定命令對象是否有綁定錯誤,有則輸出內容。需配合 spring:bind 使用。
<spring:hasBindErrors name="priceIncrease">
<b>Please fix all errors!</b>
</spring:hasBindErrors>
name(必填):命令對象 Bean 名稱。對應 BindTag。將表單字段綁定到命令對象屬性,相當於 Action 映射。常用於表單輸入與錯誤顯示。
<form method="post">
<table>
<tr>
<td>Increase (%):</td>
<spring:bind path="priceIncrease.percentage">
<td><input type="text" name="percentage"
value="<c:out value='${status.value}'/>"></td>
<td><font color="red"><c:out value="${status.errorMessage}"/></font></td>
</spring:bind>
</tr>
</table>
</form>
path(必填):綁定路徑,格式 commandName.propertyName。status:status.value 當前值、status.errorMessage 錯誤信息、status.error 是否有錯。將對象轉換為字符串顯示,利用 PropertyEditor 機制。常用於下拉框選項渲染。
國際化消息獲取,從 MessageSource 讀取:
<spring:message code="user.name" text="Default Name"/>
設置默認 HTML 轉義策略,防止 XSS:
<spring:htmlEscape defaultHtmlEscape="true"/>
主題資源解析,支持 CSS/圖片動態切換。
web.xml 註冊 DispatcherServlet,加載 Spring 上下文。<%@ taglib prefix="spring" uri="https://www.springframework.org/tags" %>Spring 標籤庫雖不如 Struts 豐富,但與 Spring MVC 數據綁定、驗證、國際化無縫集成,是構建 Spring Web 應用視圖層的利器。