Spring框架中提供了它自己的標籤庫,可以和相關的組建相結合,可以提供頁面表單組件、錯誤信息的數據綁定等功能。
如果要想使用spring標籤,要將dist目錄下的spring.tld複製到你web應用程序下的/WEB-INF/下,並在web.xml中加入
<taglib>
<taglib-uri>/spring</taglib>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
頁面
<%@taglib prefix="spring" uri="/spring"%>
<%@page contentType="text/html;charset=Big5"%>
<html>
<head><title>Login</title></head>
<body>
<spring:bind path="command.*"> //組件所有相關數據
<font color="red"><b>${status.errorMessage}</b></font><br>
</spring:bind>
輸入帳號密碼:<p>
<form name="loginform" action="/springapp/login.do" method="post">
<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> //status的expression顯示綁定的屬性名稱 value存儲的組建值
<input type="submit" value="確定"/>
</form>
</body>
</html>
使用標籤需要一個BindException對象,所以用另一個onSumit(),當驗證失敗時候,可以用BindException對象的regect()方法,意思是表示拒絕這個輸入的數據,reject()方法接受兩個參數,第一個是error code 。當然需要MessageResourceSource ,設置好你的properties資源文件中的error code爲key 寫好相應的錯誤信息。
如果沒有MessageResourceSource可以用第二個參數。
如:errors.reject("loginfail","you password is wrong");
errors.getModel()方法返回一個Map集合,之前的存儲的錯誤信息就在這裏面。可以設定給ModelAndView。這樣就會在頁面的標籤上顯示錯誤信息了。