读书人

struts2表单证验

发布时间: 2012-06-26 10:04:13 作者: rapoo

struts2表单验证

表单提交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" name="code"> <head>    <base href="<%=basePath%>">        <title>Register</title><s:head/>  </head>

?

?

具体的样式以及<s:form>经过struts2框架处理后生成的页面可以通过调试查看,样式也可以自行覆盖设置。

读书人网 >软件架构设计

热点推荐