0

我有一个从数据库检查用户名和密码的 servlet。

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
        if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
            String username = req.getParameter("usrnm");
            String userpass = req.getParameter("pwd");
            String strQuery = "select * from user where username='" + username + "' and  password='" + userpass + "'";
            System.out.println(strQuery);
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(strQuery);
            if (rs.next()) {
                req.getSession(true).setAttribute("username", rs.getString(2));
                res.sendRedirect("adminHome.jsp");
            } else {
                res.sendRedirect("index.jsp");
            }
        } else {
            res.sendRedirect("login.jsp");
        }
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

问题是浏览器只显示一个空白页面,但我希望它在重定向页面中显示“Hello World”。问题可能出在哪里?请帮我解决问题。

4

1 回答 1

4

您需要正确处理异常。您不仅应该打印它们,而且应该真正打印throw它们。

代替

    } catch (Exception e) {
        e.printStackTrace(); // Or System.out.println(e);
    }

经过

    } catch (Exception e) {
        throw new ServletException("Login failed", e);
    }

通过此更改,您现在将获得一个正常的错误页面,其中包含有关问题原因的完整堆栈跟踪。当然,您也可以只在服务器日志中挖掘以找到您刚刚打印而不是重新抛出的堆栈跟踪。

您的问题有几个可能的原因。也许是一个ClassNotFoundException或一个SQLException。所有这些都应该是不言自明和可谷歌搜索的。

也可以看看:


与具体问题无关,您的 JDBC 代码容易发生资源泄漏和 SQL 注入攻击。对此也进行研究并相应地进行修复。

于 2011-05-18T12:01:39.317 回答