I want to create a login page using servlets

17,420

Solution 1

It's unclear what you mean with "How to make it work". What happens? What happens not? At least I can spot several problems in your code:

  1. You are emitting HTML inside a servlet. You should use JSP for this.
  2. You are leaking JDBC resources. You need to close them in finally.
  3. You are not setting the entered username (and password) in the SQL string.
  4. You are not letting the DB do the task of comparing the password. Add it to the WHERE.
  5. You are swallowing the exception. All detailed info about the problem cause get lost. You should either rethrow it as ServletException or at least log the exception type, message and cause. This information is important since it tells something about the root cause of the problem. You know, once the root cause is understood, the solution is obvious.

Further it's also bad user experience if you change the page to a page where the user can do absolutely nothing else than facing an error message. The user has to take extra handling to go back to the login page to re-enter the details. Rather redisplay the same page with the error message inlined.

Rewrite your doPost() method as follows:

String userName = request.getParameter("userName");
String passWord = request.getParameter("password");

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "userdb";
String user = "root"; 
String password = "1234";
String sql = "SELECT * FROM LOGIN WHERE USR_NAME = ? AND USR_PASS = ?"; // Not sure how the password column is named, you need to check/update it. You should leave those ? there! Those are preparedstatement placeholders.

Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean login = false;

try {
    Class.forName(driver); // You don't need to call it EVERYTIME btw. Once during application's startup is more than enough.
    connection = DriverManager.getConnection(url + dbName, user, password);
    statement = connection.prepareStatement(sql);
    statement.setString(1, userName);
    statement.setString(2, password);
    resultSet = statement.executeQuery();
    login = resultSet.next();
} catch (Exception e) {
    throw new ServletException("Login failed", e);
} finally {
    if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
    if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}

if (login) {
    request.getSession().setAttribute("username", userName); // I'd prefer the User object, which you get from DAO, but ala.
    response.sendRedirect("home.jsp"); // Redirect to home page.
} else {
    request.setAttribute("message", "Unknown username/password, try again"); // This sets the ${message}
    request.getRequestDispatcher("login.jsp").forward(request, response); // Redisplay JSP.
}

And add ${message} to your JSP:

<form action="LoginPage" method="POST">
    User name: <input type="text" name="userName" size="20"><br>
    Password: <input type="password" name="password" size="20">
    <br><br>
    <input type="submit" value="Submit"> ${message}
</form>

Here are some links to learn how to do JSP/Servlet/JDBC properly.

Solution 2

you should use SELECT PASSWORD from Login in the sql query here PASSWORD is the column name which contains password in your database table LOGIN

Solution 3

toString() for request.getParameter is not required.

You can modify your query to

String sql = "SELECT <PASSWORD_CLM> FROM LOGIN WHERE USR_NAME="+userName;


while(rs.next()) 
{ 
   //read the password in pass. 
} 
if(pass !=null && pass.equals(passWord)) 
{ 
  // Code
}
Share:
17,420
sumit sharma
Author by

sumit sharma

Updated on June 25, 2022

Comments

  • sumit sharma
    sumit sharma almost 2 years

    I want to create a login page using Servlet & JSP.

    I ve created a page which gets Username & password.

    I made a database with a table which contains Username & password.

    <form action="LoginPage" method="POST">
        User name: <input type="text" name="userName" size="20"><br>
        Password: <input type="password" name="password" size="20">
        <br><br>
        <input type="submit" value="Submit">
    </form> 
    

    I entered the below code in doPost()

     response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String userName = request.getParameter("userName").toString();
        String passWord = request.getParameter("password").toString();
        Connection con = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "userdb";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root"; 
        String password = "1234";
        try {
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url+dbName, user, password);
            PreparedStatement pstmt;
            String sql = "SELECT USR_NAME FROM LOGIN WHERE USR_NAME='userName'";
            pstmt = conn.prepareStatement(sql);
            ResultSet rs=pstmt.executeQuery();
            String usr = null;
            String pass = null;
            while(rs.next())
            {
                pass = rs.getString(3);
            }
            if(pass != null && pass.equals(passWord))
            {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Login Sucessfull</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Login Sucessfull " + request.getContextPath () + "</h1>");
                out.println("<p>Welcome</p> " + userName);
                out.println("</body>");
                out.println("</html>");
    
                out.close();
            }
    
        } catch (Exception e) {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Login is not Sucessfull</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Login is not Sucessfull " + request.getContextPath () + "</h1>");
            out.println("<p>Wrong Username Or Password</p> ");
            out.println("</body>");
            out.println("</html>");
    
            out.close();
    

    And I dont know how to make it work. Any Quick Fix Available For me?

    Its not a big project, i jus want a Login page which gets username & password then the servlet will search the username in DB then checks for password. I have made the changes you guys told. But the output looks like something wrong in try block, Because, I get the Login not successful page. I put the code "Login not successful Page" in Catch block.

  • Dean
    Dean almost 14 years
    You do need to put the semi colon at the end of the SQL statement even with Prepared statements though.
  • BalusC
    BalusC almost 14 years
    @Dean: this is not true. This is only required when you want to pass multiple statements in one query. The semicolon is then the statement separator. Also note that whether it is accepted is DB dependent.