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
}
通過以上方法,可以簡化用戶輸入驗證,提高代碼的可維護性和可讀性。