JDBC-用户登录验证(解决sql注入)
解决sql注入问题
使用预编译操作对象PreparedStatement,就可以让用户输入的信息不参与sql语句的编译,问题就解决了
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.sql.*;
// 需求:实现用户登录功能
// 描述:提供一个登陆的入口,可以让用户输入用户名和密码,提交信息后,java程序收集用户信息,
// java程序连接数据库,校验用户名和密码
public class JdbcTest07 {
public static void main(String[] args) {
//1.初始化界面,创建Map集合接收用户名和密码
Map<String,String> userInfo = initUI();
//2.通过loginSuccess的值判断登陆成功与否
boolean loginSuccess = login(userInfo);
System.out.println(loginSuccess ? "登陆成功":"登陆失败");
}
private static boolean login(Map<String, String> userInfo) {
boolean loginSuccess = false;
Connection con = null;
PreparedStatement ps = null; //这里使用PreparedStatement是 sql语句预编译操作对象,经常用的
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/firstbase", "root", "123456");
String sql = "select * from t_users where username = ? and password = ?"; //使用?作为占位符,下面再给占位符传值,?不能用引号引起来
ps = con.prepareStatement(sql); // 这里使用prepaStatement方法对sql语句的框架进行预编译
String userName = userInfo.get("userName");
String password = userInfo.get("password");
ps.setString(1,userName); // 给占位符传值,jdbc中下标都是从1开始的,第一个?号就是1
ps.setString(2,password);
rs = ps.executeQuery(); //这里就不需要再传sql语句了
if (rs.next()){
loginSuccess = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return loginSuccess;
}
private static Map<String,String> initUI() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
Map<String, String> userInfo = new HashMap<>();
userInfo.put("userName", userName);
userInfo.put("password", password);
return userInfo;
}
}
When nothing seems to help, I go look at a stonecutter hammering away at his rock, perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it, but all that had gone before. -- Jacob Riis