使用JSP进行用户验证

时间:2011-12-21 20:06:59

标签: sql-server jsp validation

我正在使用HTML和JSP构建登录页面。但每当我收到错误“用户名不正确”时,如果用户名与表不匹配则应显示该错误是SQL服务器。以下是登录表单页面的代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Expense System</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>

<body>

<div class=form>

<form name = login method = post action = "login1.jsp">
Username : <input name = user type = text placeholder = username> <br><br>
Password : <input name = pass type = password placeholder = password><br><br>

<input type = submit value = "Submit">
<input type = button value = "Register">

</form>
</div>
</body>
</html>

以下是login1.jsp的代码:

<%@ page language="java" contentType="text/html; charse=UTF-8"
pageEncoding="UTF-8" import="java.sql.*"%>

<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login check</title>
</head>
<body>

<% String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
       "databaseName=signin;integratedSecurity=true;";
    Connection con = DriverManager.getConnection(connectionUrl);
    String uname = new String("");
    String upass = new String("");
    ResultSet resultset;
    Statement statement = con.createStatement();
    statement.executeQuery("select username, password from signintable");

    resultset = statement.getResultSet();

    while(resultset.next()){
        uname = resultset.getString("username");
        upass = resultset.getString("password");
    }

if(!request.getParameter("user").equals("")){
if(uname.equals(request.getParameter("user"))){
 if(upass.equals(request.getParameter("pass"))) {%>
 <jsp:forward page="welcome.html"></jsp:forward>

<% }
else {
    out.println("pass incorrect");
}
}
 else {
    out.println("username incorrect");
}
}
else { out.println("user not found!");
}
%>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

您将整个数据库表拖入Java内存并将每一行的值分配给同一个变量。这些变量最终保存表的 last 行的值。

这是不对的。您需要选择完全您需要的行。将SQL查询更改为如下所示:

PreparedStatement statement = con.prepareStatement("select id from signintable where username=? and password=?");
statement.setString(1, request.getParameter("user"));
statement.setString(2, request.getParameter("pass"));
resultSet = statement.executeQuery();

if (resultset.next()) {
    // Valid login!
} else {
    // Invalid login!
}

无关具体问题,在JSP文件中编写Java代码是poor practice。我建议你也要这样做。了解如何使用servlets

答案 1 :(得分:-1)

如果您想要详细的视图,请使用您的代码编写

if(!request.getParameter("user").equals("")) {
    if(uname.equals(request.getParameter("user"))) {
        if(upass.equals(request.getParameter("pass"))) {
            out.println("found the user name ")
        }
    }
} else {
    out.println("din't find it ");
}

您会发现在重复"din't find it "短语后会有"found the user name "