1) 重写validate方法
struts.xml
<action name="validate" class="com.struts2.demo.ValidateAction">
<result name="success">/validate.jsp</result>
<result name="input">/validate.jsp</result>
</action>
action:
public void validate() {
if (!msg.equalsIgnoreCase("hello")) {
System.out.println(INPUT);
this.addFieldError("msg.hello", "必须输入hello!");
this.addActionError("处理动作失败!");
} else {
this.addActionMessage("提交成功");
}
}
jsp:
<body>
<s:actionerror/>
<s:actionmessage/>
<s:form action="validate.action" theme="simple">
输入内容: <s:textfield name="msg"/>
<s:fielderror>
<s:param>msg.hello</s:param>
</s:fielderror>
<br/>
<s:submit value="登录" align="left"/>
<s:reset value="重填" align="left"/>
</s:form>
</body>
2) 重写validateXXX方法
struts.xml
<action name="new_validate" class="com.struts2.demo.NewValidateAction" method="regist">
<result name="input">/new_validate.jsp</result>
<result name="success">/new_validate.jsp</result>
</action>
action:
public void validateRegist() {
System.out.println("\\d匹配数字 " + "8".matches("\\d"));
if (StringUtils.isEmpty(msg)) {
addFieldError("msg", "ValidateXXX方法:用户名为必填项");
}
if (age == null || age.intValue() < 13 || age.intValue() > 20) {
addFieldError("age", "ValidateXX方法:年龄为必填项并且为数字,范围13~20间");
}
}
public String regist() {
return SUCCESS;
}
jsp:
<body>
<s:form action="new_validate.action">
<s:textfield name="msg" label="姓名"/>
<br/>
<s:textfield name="age" label="年龄"/>
<br/>
<s:submit value="提交" align="left"/>
</s:form>
</body>
3) struts框架实现
struts.xml
<action name="new_validate" class="com.iss.struts2.demo.NewValidateAction">
<result name="input">/new_validate.jsp</result>
<result name="success">/new_validate.jsp</result>
</action>
action:
public String execute() {
return SUCCESS;
}
action-validator.xml
<validators>
<field name="msg">
<field-validator type="requiredstring">
<message>请输入姓名</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">13</param>
<param name="max">20</param>
<message>
必须在13~20之间
</message>
</field-validator>
</field>
</validators>
jsp:
<body>
<s:form action="new_validate.action">
<s:textfield name="msg" label="姓名"/>
<br/>
<s:textfield name="age" label="年龄"/>
<br/>
<s:submit value="提交" align="left"/>
</s:form>
</body>