i am building a login page using HTML and JSP. But every time i get the error “username incorrect” which should be shown when the username does not match with the table is SQL server. Here is the code for login form page:
<%@ 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>
Below is the code for 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>
You’re hauling the entire database table into Java’s memory and assigning the value of every single row to the same variable. Those variables end up holding the values of the last row of the table.
This is not right. You need to select exactly the row you need. Change your SQL query to something like as follows:
Unrelated to the concrete problem, writing Java code inside a JSP file is a poor practice. I suggest you to work on that as well. Learn how to use servlets.