1、校验用户名、密码格式
在注册时通常要验证用户名和密码是否合法,运用学习过的知识完成如下操作:
用户名长度6-12位,必须包含数字和英文字母
密码长度8-20位,必须包含特殊符合_或者$,英文字母以及数字
以上两个条件同时成立注册才能成功
public class Register {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("请输入账号:");
String uname = sc.nextLine();
if (uname.length()<6||uname.length()>12) {
System.out.println("用户名长度不合法");
continue; //跳过循环体中剩余的语句而强制执行下一次循环操作
}
boolean x = false;
boolean y = false;
char[] ch = uname.toCharArray();
for (int i = 0; i < uname.length(); i++) {
char a = ch[i];
if(a>='0'&&a<='9') {
x = true;
continue;
}
if((uname.charAt(i)>='a'&&uname.charAt(i)<='z') || (uname.charAt(i)>='A'&&uname.charAt(i)<='Z')) {
y = true;
}
}
if(x&&y) {
System.out.println("用户名合法:"+uname);
break; //从循环体内中途跳出循环体,接着执行循环下面的语句
}
}
while(true) {
System.out.print("请输入密码:");
String pwd = sc.nextLine();
if (pwd.length()<8||pwd.length()>20) {
System.out.println("密码长度不合法");
continue;
}
boolean x = false;
boolean y = false;
boolean z = false;
char[] ch = pwd.toCharArray();
for (int i = 0; i < pwd.length(); i++) {
char a = ch[i];
if(a>='0'&&a<='9') {
x = true;
continue;
}
if((pwd.charAt(i)>='a'&&pwd.charAt(i)<='z') || (pwd.charAt(i)>='A'&&pwd.charAt(i)<='Z')) {
y = true;
continue;
}
if (pwd.contains("_") || pwd.contains("$")) {
z = true;
}
}
if(x&&y&&z) {
System.out.println("密码合法:"+pwd);
break;
}
}
}
}
2、校验数据库中是否存在该用户
public class RegisterDemo3 {
public static void main(String[] args) {
register();
}
public static void register() {
System.out.println("注册页面");
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String uname = sc.nextLine();
if(checkUsername(uname)) {
return;
}
System.out.println("请输入密码子:");
String pwd = sc.nextLine();
String sql = "insert into user(id,uname,password) values(null,?,?)";
Connection conn = JDBCUtils.getConnection();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, uname);
ps.setObject(2, pwd);
int i = ps.executeUpdate();
if(i>0) {
System.out.println("注册成功,页面跳转");
} else {
System.out.println("注册失败!!!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeAll(null, ps, conn);
}
}
private static boolean checkUsername(String uname) {
boolean flag = true;
//存在sql注入漏洞(伪真语句 ...' or '1'='1),解决用?做占位符
//String sql = "select * from user where uname='"+uname+"'";
String sql = "select * from user where uname =?";
Connection conn = JDBCUtils.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, uname);
rs = ps.executeQuery();
if(rs.next()) {
System.out.println("该用户名已存在,请更换其他用户名");
} else {
System.out.println("该用户名可用!");
flag = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeAll(rs, ps, conn);
}
return flag;
}
}