我正在使用HTML和JSP构建登录页面。但每次我得到错误“用户名不正确”,当用户名与表不匹配时,应显示为SQL服务器。下面是登录表单页面的代码:使用JSP进行用户验证
<%@ 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>
每次有人登录时,将应用程序的整个表格循环回来并不是一个好主意!您应该调查具有WHERE条件的参数化查询,以选择特定的感兴趣的行(如果存在并散列密码)。 – 2011-12-21 20:11:27
在Java中使用类似'String uname = new String(“”);'和'String upass = new String(“”);'的语句总是可以避免的,因为您创建的是新对象而不是实习那些字符串一个不好的做法。只需使用String uname =“”和'String upass =“”'。在这种情况下,你正在汇集这些字符串对象。 – Lion 2011-12-21 20:15:41
@MartinSmith我使用WHERE条件,但我能够成功地运行我的程序。但是我想要做的是首先检查用户名,如果它是正确的,那么检查密码。如何使用WHERE条件来做到这一点。谢谢。 – 2011-12-21 20:22:24