我有一个从数据库检查用户名和密码的 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”。问题可能出在哪里?请帮我解决问题。
您需要正确处理异常情况。你不仅应该打印它们,而且真的应该throw
them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
通过此更改,您现在将获得一个正常的错误页面,其中包含有关问题原因的完整堆栈跟踪。当然,您也可以在服务器日志中挖掘以查找您刚刚打印而不是重新抛出的堆栈跟踪。
您的问题有多种可能的原因。也许是一个ClassNotFoundException
or a SQLException
。所有这些都应该是不言自明的并且可以通过谷歌搜索。
也可以看看:
- 我应该如何在基于 servlet 的应用程序中连接到 JDBC 数据库/数据源? https://stackoverflow.com/questions/2299469/how-should-i-connect-to-jdbc-database-datasource-in-a-servlet-based-applicatio
- 如何在Eclipse Web项目中安装JDBC驱动程序而不面临java.lang.ClassNotFoundException https://stackoverflow.com/questions/2353141/how-to-install-jdbc-driver-in-eclipse-web-project-without-facing-java-lang-class
- 臭名昭著的 java.sql.SQLException: 找不到合适的驱动程序 https://stackoverflow.com/questions/1911253/the-infamous-java-sql-sqlexception-no-suitable-driver-found
无关具体问题是,您的 JDBC 代码很容易遭受资源泄漏和 SQL 注入攻击。对此也进行研究并进行相应的修复。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)