我有一个 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);
}
由
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
通过此更改,您现在将获得一个正常的错误页面,其中包含有关问题原因的完整堆栈跟踪。当然,您也可以在服务器日志中挖掘以查找您刚刚打印而不是重新抛出的堆栈跟踪。
导致您的问题的可能原因有多种。可能是 ClassNotFoundException
或 SQLException
。所有这些都应该是不言自明的并且可以在谷歌上搜索到。
另请参阅:
- How should I connect to JDBC database / datasource in a servlet based application?
- How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
- The infamous java.sql.SQLException: No suitable driver found
与具体问题无关,您的 JDBC 代码很容易遭受资源泄漏和 SQL 注入(inject)攻击。对此也进行研究并进行相应的修复。
关于servlets - 向与数据库交互的 Servlet 提交表单会导致空白页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61967419/