全部,
我编写了一个 java 代码,需要检查用户使用控制台输入的文本,我希望代码测试输入的行不超过例如 20 个字母,我写如下:
String getName() {
boolean badName = true;
String Name = "";
Scanner console = new Scanner(System.in);
while (badName ){
System.out.println("Please enter your first name ");
Name = console.nextLine();
//^ I want to check this string length while the user enters the line
// to prevent DOS attack when an attacker tries to enter very large line
if (console.nextLine().length > 20) {
//^ I tried this but could not get the string value after this condition validated,
// I dont want to store it in a variable to not cause DOS attack.
System.out.println("please enter valid name!!!");
continue;
}
if (! Name.matches ("[a-zA-Z_]+")) {
System.out.println("the name contains invalid character, please try again :");
continue;
}
if (Name.matches ("[a-zA-Z_]+")){
badName = false;
}
}
return Name;
}
不确定我是否真的需要检查以防止 DOS 攻击,或者 Java 通常会处理这个问题?
谢谢,