User.java
private String userName; private String userPassword; private Integer userNo; private Date userRegisterDate; //setter/getter...
LoginAction.java,Step2完全沒有覆寫
private User user = new User(); public User getUser() { return user; }
struts.xml,Step4說不用method
<action name="login" class="login.LoginAction"> <result name="success">/struts2/login.jsp</result> <result name="input">/struts2/login.jsp</result> </action>
login.jsp
${fieldErrors} <s:property value="displayMessage" /> <form action="login.action"> 帳號:<input type="text" name="user.userName" />${FieldErrors["user.userName"][0]}<br /> 密碼:<input type="password" name="user.userPassword" />${FieldErrors["user.userPassword"][0]}<br /> 學號:<input type="text" name="user.userNo" />${FieldErrors["user.userNo"][0]}<br /> 註冊日期:<input type="text" name="user.userRegisterDate" />${FieldErrors["user.userRegisterDate"][0]}<br /> <input type="reset" /> <input type="submit" /> </form>
LoginAction-validation.xml,Step3要注意命名方式,放在Action同層
<field name="user.userName"> <field-validator type="requiredstring"> <message>You must enter a userName</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">10</param> <message>帳號長度必需在${minLength}到${maxLength}之間</message> </field-validator> </field> <field name="user.userPassword"> <field-validator type="requiredstring"> <message>密碼必須輸入</message> </field-validator> </field> <field name="user.userNo"> <field-validator type="requiredstring" short-circuit="true">
<message>學號必須輸入</message> </field-validator> <field-validator type="int"> <param name="min">1</param> <param name="max">1000</param> <message>學號必需介於${min}到${max}之間</message> </field-validator> </field> <field name="user.userRegisterDate"> <field-validator type="requiredstring"> <message>註冊日期必須輸入</message> </field-validator> <field-validator type="date"> <param name="min">01/01/1990</param> <param name="max">01/01/2000</param> <message>註冊日期必需介於${min}到 ${max}之間</message> </field-validator> </field>
short-circuit="true",表示如有錯,就不往下驗證了
我試的結果,只有必輸有起作用,int和date會出現「Invalid field value for field "XXX".」
但聽說正式開發很少人用這個框架
找到了這個後,我新增一個LoginAction.properties,放在Action同一層
invalid.fieldvalue.user.userNo=\u5B78\u865F\u5FC5\u9700\u4ECB\u65BC 1 \u5230 1000 \u4E4B\u9593 invalid.fieldvalue.user.userRegisterDate=\u8A3B\u518A\u65E5\u671F\u5FC5\u9700\u4ECB\u65BC 1990-01-01 \u5230 2000-01-01 \u4E4B\u9593
然後LoginAction-validation.xml不改也是可以,只是
沒有留言:
張貼留言