第一种验证方式:(有局限性,有很多字段的话就不好用了)
1、在页面中用<s:fielderror></s:fielderror>标签显示错误信息,
如果struts.xml中定义了<constant name="struts.ui.theme" value="simple"/> 就一定要加<s:fielderror/>否 则是不会显示错误信息的
如果没有定义,那么如果用struts2标签后,会自动在对应的组件后面显示验证的错误信息
2、在action中写validate方法
public void validate() {
if(this.username.equals("")){
this.addFieldError("username", "用户名不能为空");
}
if(this.password.equals("")){
this.addFieldError("password", "密码不能为空");
}else if(this.password.length()<6){
this.addFieldError("password", "密码长度不能小于6");
}
}
其中的"username","password"和表单中的name的属性对应
3、在配置文件中:
<result name="input">validate.jsp</result> input是固定写法第二种验证方式:(验证某一个方法,所用到的字段)
public void validateXxx(){ xxx为当前请求的action中的方法
//写验证逻辑}
要被验证的表单:
<s:form action="testValidate" method="post">
<s:textfield name="username" label="用户名"/>
<s:password name="password" label="密码"/>
<s:submit label="提交"/>
<!-- 如果在struts.xml配置文件中没有设置使用simple主题,s:fielderror可不写,不写也有验证提示信息 -->
<s:fielderror/>
</s:form>
Action:
public class TestValidateAction extends ActionSupport implements Serializable {
private String username;
private String password;
public String execute() {
return SUCCESS;
}
/**
* 验证方法一:
*/
public void validate() {
if(this.username.equals("")){
this.addFieldError("username", "用户名不能为空");
}
if(this.password.equals("")){
this.addFieldError("password", "密码不能为空");
}else if(this.password.length()<6){
this.addFieldError("password", "密码长度不能小于6");
}
}
/**
* 验证方法二:
*/
public void validateExecute(){
if(this.username.equals("")){
this.addFieldError("username", "用户名不能为空");
}
if(this.password.equals("")){
this.addFieldError("password", "密码不能为空");
}else if(this.password.length()<6){
this.addFieldError("password", "密码长度不能小于6");
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}