1

I just started to play around with servlets and trying to implement a simple java-based authentication system. I have a login form through which send the login data and if its correct redirect to home page. The login form is like in below code:

<form name="frmLogin" action="/LogonServlet" method="POST">
    <table border="1">
        <tr>
            <td colspan="2"><c:out value="${errorMsg}"/> </td></tr>
        <tr>
            <td>User Name: </td>
            <td><input type="text" name="username" /></td></tr>
        <tr>
            <td>Password: </td>
            <td><input type="password" name="password" /></td></tr>
        <tr>
            <td><input type="submit" name="Submit" value="Submit"/></td></tr>
    </table>
</form>

The directory structure:

enter image description here

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>TestProject</display-name>
    <servlet>
        <display-name>LogonServlet</display-name>
        <servlet-name>LogonServlet</servlet-name>
        <servlet-class>test.cc.project.LogonServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogonServlet</servlet-name>
        <url-pattern>/LogonServlet</url-pattern>
    </servlet-mapping>
</web-app>

The result is:

HTTP Status 404 - /LogonServlet

type Status report
message /LogonServlet
description The requested resource is not available.

Can anyone explain me where I should put the class in order to call it correctly? Thanks.

UPDATE:

LogonServlet.java

@WebServlet("/LogonServlet")
public class LogonServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String DB_USERNAME = "test";
private static final String DB_PASSWORD = "test";
private static final String LOGIN_QUERY = "SELECT * FROM `accounts` WHERE uname=? AND passwd=?";

private static final String HOME_PAGE = "../Home.jsp";
private static final String LOGIN_PAGE = "../Login.jsp";

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String strUserName = request.getParameter("username");
    String strPassword = request.getParameter("password");
    String strErrMsg = null;
    HttpSession session = request.getSession();
    boolean isValidLogon = false;

    try {
        isValidLogon = authenticateLogin(strUserName, strPassword);
        if(isValidLogon) {
            session.setAttribute("username", strUserName);
        } else {
            strErrMsg = "Username or Password is invalid. Please try again.";
        }
    } catch(Exception e) {
        strErrMsg = "Unable to validate user/password in database";
    }

    if(isValidLogon) {
        response.sendRedirect(HOME_PAGE);
    } else {
        session.setAttribute("errorMsg", strErrMsg);
        response.sendRedirect(LOGIN_PAGE);
    }

}

private boolean authenticateLogin(String strUserName, String strPassword) throws Exception {
    boolean isValid = false;
    Connection conn = null;

    try {
        conn = getConnection();
        PreparedStatement prepStmt = conn.prepareStatement(LOGIN_QUERY);
        prepStmt.setString(1, strUserName);
        prepStmt.setString(2, strPassword);
        ResultSet rs = prepStmt.executeQuery();
        if(rs.next()) {
            System.out.println("User login is valid in DB");
            isValid = true;
        }
    } catch(Exception e) {
        System.out.println("validateLogon: Error while validating password: " +e.getMessage());
        throw e;
    } finally {
        closeConnection(conn);
    }

    return isValid;
}

private Connection getConnection() throws Exception {
    Connection conn = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
        if (conn != null) {
            System.out.println("Connected to the database");
        }
    } catch(SQLException sqle) {
        System.out.println("SQLException: Unable to open connection to DB: " +sqle.getMessage());
        throw sqle;
    } catch(Exception e) {
        System.out.println("Exception: Unable to open connection to DB: " +e.getMessage());
        throw e;
    }

    return conn;
}

private void closeConnection(Connection conn) {
    try {
        if(conn!=null && !conn.isClosed()) {
            conn.close();
        }
    } catch(SQLException sqle) {
        System.out.println("Error while closing connection.");
    }
}

}
bofanda
  • 10,386
  • 8
  • 34
  • 57
  • Try `action="LogonServlet"` (no slash), because I guess the webapp might not be deployed in `/` on the server, and the servlet is relative to the JSP that has the form on it - have a look at the URL in the browser. – jCoder Dec 07 '13 at 16:36
  • @jCoder Thank you for your reply, following your suggestion met me with the `HTTP Status 500 - Error instantiating servlet class` error. Any ideas? – bofanda Dec 07 '13 at 17:52
  • Show your servlet code. – David Levesque Dec 07 '13 at 18:10
  • @DavidLevesque The servlet code is included to the `UPDATE` part of the question. – bofanda Dec 07 '13 at 18:48
  • Check the log for exceptions, e.g. if your database connection is not valid or the select fails, the server might respond with a 500 error if you (re-)throw an exception. Also, you may want to debug your servlet code to narrow down the error. – jCoder Dec 07 '13 at 19:13

1 Answers1

3
  1. you are calling /LogonServlet then you redirect to ../Home.jsp and ../Login.jsp
  2. remove the "/" from web.xml
  3. remove the line "@WebServlet("/LogonServlet")" which is a duplicate definition in respect of web.xml

finally let me suggest to NOT use custom login, use Realm and JEE authentication module it is easier and more portable

venergiac
  • 7,469
  • 2
  • 48
  • 70
  • thanks for the suggestion, the problem was with dots `../Home.jsp and ../Login.jsp`. Usage of Realm & JEE authentication I noted for my future experience. The answer accepted. – bofanda Dec 16 '13 at 23:51