我在进行密码验证方面遇到了麻烦。我从名为applicationconstants的java类中获取密码范围的最小值和最大值,并在servlet中调用它。我在另一个java类中使用验证函数并在servlet中调用它。请帮我解决这个问题。
servlet代码
int minLength = ApplicationConstants.PASSWORD_MIN_LENGTH;
int maxLength = ApplicationConstants.PASSWORD_MAX_LENGTH;
if (user.getUserPassword().length() > 0 || user.getUserPassword() !=null) {
if (Validation.validateStringLengthRange(user.getUserPassword(), minLength, maxLength)) {
System.out.println("servlet");
isvalidate = false;
hashMap.put("password", props.getText("error.password.compare.outofrange"));
session.setAttribute("errorMessage", hashMap);
}
}
Validation.java
public static boolean validateStringLengthRange(String name, int min, int max) {
boolean isValid = true;
int len = name.length();
if (len > 0) {
if (len < min || len > max) {
System.out.println("validation.java");
isValid = false;
}
}
return isValid;
}
ApplicationConstants.java
public static final int PASSWORD_MIN_LENGTH = 6;
public static final int PASSWORD_MAX_LENGTH = 18;
答案 0 :(得分:5)
盲目尝试,因为paxdiablo说你没有指明问题
如果问题是你得到NullPointerException,请仔细检查这一行
if (user.getUserPassword().length() > 0 || user.getUserPassword() !=null) {
并将其更改为
if (user.getUserPassword() !=null && user.getUserPassword().length() > 0) {
那应该解决它;)
答案 1 :(得分:2)
Validation.validateStringLengthRange(user.getUserPassword(), minLength, maxLength))
如果有效,返回true。因此,如果它无效,您可能需要输入错误消息:
if (!Validation.validateStringLengthRange(user.getUserPassword(), minLength, maxLength)) {
isvalidate = false;
请注意!
。
答案 2 :(得分:1)
好的,如果密码已经过验证,validateStringLengthRange
会返回true,但如果结果为true,您似乎正在调用错误逻辑 - 是否缺少“not”运算符,即Validation.validateStringLengthRange
是!Validation.validateStringLengthRange
?
另外,你需要在检查长度之前进行空检查,我猜即使输入为空也应该是一个错误,那么如何:
String password = user.getUserPassword();
if (password == null || password.length() == 0 ||
!Validation.validateStringLengthRange(password, minLength, maxLength)) {
System.out.println("servlet");
isvalidate = false;
hashMap.put("password", props.getText("error.password.compare.outofrange"));
session.setAttribute("errorMessage", hashMap);
}