struts 2フォーム検証
2010 ワード
フォーム提出JSP-register.jsp:
検証フォームメソッド:対応するactionにvalidateメソッドを追加します.
検証メソッドのいずれかが成立した場合、の結果タイプが返されます.
Struts 2では、struts.xmlに次の構成を追加します.
すると、エラーメッセージが表示されます.エラーメッセージにスタイルを設定するには、register.jspに...にを追加します.具体的には、次のようにします.
具体的なスタイルおよびstruts 2フレームワーク処理後に生成されたページはデバッグで表示でき、スタイルは自分で設定を上書きすることもできます.
<s:form action="register">
<s:textfield name="personBean.firstName" label="firstName"></s:textfield>
<s:textfield name="personBean.lastName" label="lastName"></s:textfield>
<s:textfield name="personBean.email" label="email"></s:textfield>
<s:textfield name="personBean.age" label="age"></s:textfield>
<s:submit></s:submit>
</s:form>
検証フォームメソッド:対応するactionにvalidateメソッドを追加します.
public void validate(){
if(personBean.getFirstName().length() == 0){
this.addFieldError("personBean.firstName", "First Name is required." );
}
if(personBean.getLastName().length() == 0){
this.addFieldError("personBean.lastName", "Last Name is required.");
}
if(personBean.getAge() < 18){
this.addFieldError("personBean.age", "Age is required and must be 18 or older");
}
}
検証メソッドのいずれかが成立した場合、
Struts 2では、struts.xmlに次の構成を追加します.
<action name="register" class="com.hs.guofc.action.Register">
<result>/thankyou.jsp</result>
<result name="input">/register.jsp</result>
</action>
すると、エラーメッセージが表示されます.エラーメッセージにスタイルを設定するには、register.jspに...に
<head>
<base href="<%=basePath%>">
<title>Register</title>
<s:head/>
</head>
具体的なスタイルおよび