I am processing following code for resolving login credentials from servlet.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
@WebServlet("/login")
public class oneServlet extends HttpServlet {
public static Connection getConnection() throws Exception {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://10.1.11.112:5432/pack";
String username = "pack";
String password = "pack";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
System.out.println("done 1");
Connection conn = null;
PreparedStatement pstmt = null;
System.out.println("done 2");
try {
conn = getConnection();
String queryTest = "select username,password from login ";
pstmt = conn.prepareStatement(queryTest);
System.out.println("done 3");
ResultSet rs = pstmt.executeQuery();
System.out.println("done4");
while (rs.next()) {
System.out.println("done5");
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
response.sendRedirect("LoginSuccess.jsp");
return;
}
else
{
JOptionPane.showMessageDialog(null, "retry");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
the problem i am facing is that “while (rs.next())” is iterating and showing output for every username available in table , but i need it to be displayed only once , either redirect or retry. Any suggestion are appreciated.
You’re unnecessarily copying the entire DB table into Java’s memory instead of writing the SQL query in such way that the DB returns exactly the row you’re looking for, so that you can just get away with
if (resultSet.next()).Make use of the SQL
WHEREclause.Note that I also fixed the insane way of displaying a message and fixed the exception handling and the closing of DB resources. The
JOptionPanewould only display the message to webserver’s screen, not to webbrowser’s screen, which would of course fail in real production environment when they do not run at physically the same machine. I strongly recommend to stop reading roseindia.net tutorials. That site is cluttered of bad practices like as exposed in your code.See also: