Servlets 将表单提交到与数据库交互的Servlet会导致出现空白页面

Servlets 将表单提交到与数据库交互的Servlet会导致出现空白页面,servlets,database-connectivity,Servlets,Database Connectivity,我有一个servlet,可以从数据库中检查用户名和密码 @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = Driv

我有一个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”。问题出在哪里?请帮助我排除故障。

您需要正确处理异常。您不仅应该打印它们,还应该真正地抛出它们

替换

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

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

您的问题有几个可能的原因。可能是
ClassNotFoundException
SQLException
。所有这些都应该是自我解释和谷歌

另见:


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

从服务器上发布异常/错误日志耶!非常感谢,兄弟。我改为`}catch(Exception e){throw new ServletException(“Login failed”,e);}`并且我得到一个异常显示,显示我的数据库名称不存在。我有mvs_用户用于数据库,但实际名称是mvs_用户。很高兴有你这样的编程头脑。干杯
    } catch (Exception e) {
        throw new ServletException("Login failed", e);
    }