我想在用戶登錄到另一頁後從當前頁面(index.jsp)重定向。我沒有得到這個錯誤,也不能真正理解問題所在。這是我的servlet代碼:request.sendRedirect不起作用
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
usernameInput = request.getParameter("username");
passwordInput = request.getParameter("password");
Connection conn = null;
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
String sql;
sql = "SELECT * FROM `users` where Username=? and Password=?";
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, usernameInput);
prepStmt.setString(2, passwordInput);
ResultSet rs = prepStmt.executeQuery();
if (rs.next()) {
System.out.println("User login is valid in DB");
//Here is where I try to log in. I tryed both the commented and uncommented way to log in but none seems to work.
response.sendRedirect(request.getContextPath() + "resources/main.jsp");
/*RequestDispatcher reqDisp = request.getRequestDispatcher("../WebContent/resources/main.jsp");
reqDisp.forward(request, response);*/
}
} catch (Exception e) {
System.out.println("validateLogon: Error while validating password: " + e.getMessage());
try {
throw e;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我可以驗證它的代碼的特定部分進入,因爲我在consele消息印刷看到。如果我能猜到這個問題,那可能是我沒有給出正確的路徑。這是我的項目的結構。
任何想法?謝謝!
好吧,你知道重定向是什麼嗎?打開瀏覽器中的開發工具,查看瀏覽器爲響應重定向而實際嘗試加載的URL。 http://stackoverflow.com/questions/20371220/what-is-the-difference-between-response-sendredirect-and-request-getrequestdis –