Java - 如何实现区分大小写的用户名和密码

时间:2015-10-04 18:19:03

标签: java mysql oauth case-sensitive

所以我创建了这个登录表单,其中凭据(用户名和密码)存储在MYSQL中。我希望用户名和密码是案例性的。

AuthDAO.java

public static int checkUserPass(String username, String password){
    int userId = -1;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        cn = DriverManager.getConnection("jdbc:mysql://localhost/b440", "root", "b440");

        String q="SELECT userId FROM user WHERE username='"+username+"' AND password='"+password+"'";

        Statement st = cn.createStatement();
        ResultSet rs = st.executeQuery(q);
        while(rs.next()){
            userId=Integer.parseInt(rs.getString("userId"));
        }
        rs.close();
        st.close();         
    }catch(Exception e){
        System.err.println(e.getMessage());
        e.printStackTrace();
    }
    DB_close();
    if(userId!=-1)
        return userId;
    return -1;
}

LoginServlet.java

else{
    int ID = checkUserPass(username, password, role);
    if(ID!=-1 ){ //User Is Legit!!
        loggedIn = "true";
        HttpSession se = request.getSession();
        se.setAttribute("user", getUserById(ID));
        se.setAttribute("loggedIn", loggedIn);
        url = "/index.jsp";
        msg = "Login Successful!";

        request.setAttribute("loggedIn", loggedIn);
        request.setAttribute("msg", msg);
    }
    else{
        msg = "Invalid Login, please check username or password";
        url = "/login.jsp";
        loggedIn = "false";
        request.setAttribute("loggedIn", loggedIn);
        request.setAttribute("msg", msg);           
    }       

1 个答案:

答案 0 :(得分:2)

默认情况下,mysql查询不区分大小写。

虽然你可以像这样使用BINARY -

SELECT userId FROM user WHERE BINARY username='"+username+"' AND  BINARY password='"+password+"'

或者还有其他一些方法 -

http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html