ActionForm是Struts框架中用于处理用户输入的Java类。简化用户输入验证可以通过以下方法实现:
public class MyForm extends ActionForm {
private String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
// 使用内置的required验证器
public boolean validate() {
if (username == null || username.trim().length() == 0) {
addFieldError("username", "用户名不能为空");
return false;
}
return true;
}
}
public class MyForm extends ActionForm {
private String username;
private static final int MIN_LENGTH = 4;
private static final int MAX_LENGTH = 20;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
// 自定义验证方法
public boolean validateUsername() {
if (username == null || username.length() < MIN_LENGTH || username.length() > MAX_LENGTH) {
addFieldError("username", "用户名长度必须在" + MIN_LENGTH + "到" + MAX_LENGTH + "之间");
return false;
}
return true;
}
}
<!-- 引入Hibernate Validator依赖 -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
import javax.validation.Valid;
public class MyForm extends ActionForm {
@Valid
private UserInfo userInfo;
// getters and setters
}
public class UserInfo {
@NotNull(message = "用户名不能为空")
private String username;
@NotNull(message = "密码不能为空")
@Size(min = 6, max = 20, message = "密码长度必须在6到20之间")
private String password;
// getters and setters
}
通过以上方法,可以简化用户输入验证,提高代码的可维护性和可读性。