表单提交JSP——register.jsp:
<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");
}
}
如果验证方法有任何一项成立,则会返回<result name="input">的结果类型。
Struts2的做法是,在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>...</head>内添加<s:head>,具体如下:
<head>
<base href="<%=basePath%>">
<title>Register</title>
<s:head/>
</head>
具体的样式以及<s:form>经过struts2框架处理后生成的页面可以通过调试查看,样式也可以自行覆盖设置。
3701

被折叠的 条评论
为什么被折叠?



