Java HTTP状态404-请求的资源不可用。一个简单的servlet认证系统

Java HTTP状态404-请求的资源不可用。一个简单的servlet认证系统,java,eclipse,authentication,servlets,Java,Eclipse,Authentication,Servlets,我刚刚开始使用servlet,并尝试实现一个简单的基于java的身份验证系统。我有一个登录表单,通过该表单发送登录数据,如果正确,则重定向到主页。登录表单如以下代码所示: <form name="frmLogin" action="/LogonServlet" method="POST"> <table border="1"> <tr> <td colspan="2"><c:out value=

我刚刚开始使用servlet,并尝试实现一个简单的基于java的身份验证系统。我有一个登录表单,通过该表单发送登录数据,如果正确,则重定向到主页。登录表单如以下代码所示:

<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>
有人能告诉我应该把班级放在哪里才能正确地调用它吗?谢谢

更新:

HTTP Status 404 - /LogonServlet

type Status report
message /LogonServlet
description The requested resource is not available.
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.");
    }
}

}
  • 您正在调用/LogonServlet,然后重定向到../Home.jsp和../Login.jsp
  • 从web.xml中删除“/”
  • 删除行“@WebServlet(“/LogonServlet”)”,这是web.xml的重复定义

  • 最后,我建议不要使用自定义登录,使用Realm和JEE身份验证模块。它更简单、更便于携带

    请尝试
    action=“LogonServlet”
    (无斜杠),因为我猜webapp可能不会部署在服务器上的
    /
    中,servlet与包含表单的JSP相关-请在浏览器中查看URL。@jCoder感谢您的回复,根据您的建议,我遇到了
    HTTP状态500-错误实例化servlet类
    错误。有什么想法吗?显示您的servlet代码。@DavidLevesque servlet代码包含在问题的
    更新部分。检查日志中是否有异常,例如,如果您的数据库连接无效或选择失败,如果您(重新)抛出异常,服务器可能会响应500错误。此外,您可能需要调试servlet代码以缩小错误范围。感谢您的建议,问题在于dots
    。/Home.jsp和../Login.jsp
    。Realm和JEE认证的使用是我为将来的体验而注意的。答案被接受了。
    @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.");
        }
    }
    
    }