2016-08-30 22 views
-1

我想在用戶登錄到另一頁後從當前頁面(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消息印刷看到。如果我能猜到這個問題,那可能是我沒有給出正確的路徑。這是我的項目的結構。

enter image description here

任何想法?謝謝!

+1

好吧,你知道重定向是什麼嗎?打開瀏覽器中的開發工具,查看瀏覽器爲響應重定向而實際嘗試加載的URL。 http://stackoverflow.com/questions/20371220/what-is-the-difference-between-response-sendredirect-and-request-getrequestdis –

回答

1

據位於here的HttpServletRequest的API:

路徑以「/」字符開頭,但不以「/」字符結束。

因此您的線路

response.sendRedirect(request.getContextPath() + "resources/main.jsp"); 

可輸出一些混搭在一起字符串,它是不是你的預期路徑。嘗試調試request.getContextPath()+「resources/main.jsp」的結果,並查看它是否是你想要的結果。您可能需要到該行更改爲:

response.sendRedirect(request.getContextPath() + "/resources/main.jsp"); 

無關,但使用的doGet可能不是這裏最好的主意,因爲一個GET請求的參數將被包含在URL中 - 包括您的用戶明文密碼。

+0

這並不適用於我 – Panos

+0

什麼是System.out.println( request.getContextPath()+「resources/main.jsp」); –

+0

結果如下:/Sample_LogIn_Page/resources/main.jsp – Panos