數據綁定的幾個方法


您可以一次綁定表單物件的一個屬性與數值,例如:
...
<spring:bind path="command.username">
名稱 <input type="text"
             name="\${status.expression}"
             value="\${status.value}"/><br>
</spring:bind> 
  
<spring:bind path="command.password">
密碼 <input type="password"
             name="\${status.expression}"
             value="\${status.value}"/><br>
</spring:bind>
...

"expression"會顯示被綁定的屬性名稱,而value則顯示被綁定的屬性值。

或者是這麼綁定Command:
...
<spring:bind path="command">
名稱 <input type="text"
             name="username"
             value="\${command.username}"/><br>

密碼 <input type="password"
             name="password"
             value="\${command.password}"/><br>
</spring:bind>
...

對於錯誤訊息,之前用BindException中的reject()方法,這個方法並不會區分特定欄位錯誤訊息,您可以使用rejectValue()方法來加入錯誤訊息:
rejectValue(String field, String errorCode,
              Object[] errorArgs, String defaultMessage)
rejectValue(String field, String errorCode,
              String defaultMessage)

rejectValue()的field參數讓您指定表單物件的屬性,errorCode參數指定資源檔案中的鍵(Key),errorArgs參數用於指定資源檔案中的佔位字元,而預設訊息則是使用於找不到資源檔案時所要呈現的預設訊息。一個使用例子如下:
....
public void ModelAndView(....,
                    BindException errors) throws Exception {
    ...
    errors.rejectValue("username",
                    "error", null, "使用者名稱錯誤");
    ...
    errors.rejectValue("password", "error", null, "密碼錯誤");

    return new ModelAndView(
                    this.getFormView(), errors.getModel());
}
...

如上面的程式片段中加入之訊息,可以使用綁定標籤來呈現訊息:
...
<spring:bind path="command.username">
名稱 <input type="text"
             name="\${status.expression}"
             value="\${status.value}"/><br>
<font color="red">\${status.errorMessage}</color>
</spring:bind>

<spring:bind path="command.password">
密碼 <input type="password"
             name="\${status.expression}"
             value="\${status.value}"/><br>
<font color="red">\${status.errorMessage}</color>
</spring:bind>
...

相應的錯誤訊息會綁定至相關的欄位上,如果同一個屬性上被綁定了錯誤訊息,則可以使用\${status.errorMessages}取出,可以搭配JSTL來輸出訊息,例如:
...
<spring:bind path="command.username">
名稱 <input type="text"
             name="\${status.expression}"
             value="\${status.value}"/><br>
<c:if test="\${status.error}">
    <font color="red">
    錯誤:<br>
        <c:forEach items="\${status.errorMessages}"
                     var="error">
            <c:out value="\${error}"/><br>
        </c:forEach>
    </font>
</c:if>
</spring:bind>
...

\${status.error}可以用於測試是否有錯誤訊息,也可以使用<spring:hasBindErrors>來決定是否輸出某些內容,例如:
...
<spring:hasBindErrors>
    發現以下的錯誤,請更正。。。
    ......
</spring:hasBindErrors>
...


或者您也可以不區分表單物件屬性,一次輸出所有的錯誤訊息,例如:
....
<spring:bind path="command.*">
    <font color="red">
    錯誤:<br>
        <c:forEach items="\${status.errorMessages}"
                     var="error">
            <c:out value="\${error}"/><br>
        </c:forEach>
    </font>
</spring:bind>
...