2014-08-31 28 views
0

我有一個servlet來處理/Login使用Servlet登錄後重定向到index.jsp

String tempUsername = request.getParameter("username").trim(); 
String tempPassword = request.getParameter("password").trim(); 
String message = null; 

if(tempUsername != null && tempPassword != null) { 
    String username = tempUsername; 
    String password = tempPassword; 
    Staff staff = new Staff(); 

    try { 
     Facade facade = new Facade(); 
     Staff result = facade.getStaff(username, password); 

     if(result != null) { 
      // response.sendRedirect(request.getContextPath()+"/Home"); // Success but didn't redirect to `/Home` 
      System.out.println("Success"); 
     } 
     else { 
      // request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); 
      System.out.println("Fail"); 
     } 
    } 
    catch(SQLException | NamingException e) { 
     // SQL Error 
    } 
    finally { 
     request.setAttribute("message", message); 
    } 

} 
else { 
    // Empty field(s) 
} 

我還有一個servlet來處理/Home如果登錄成功,其中index.jsp將被顯示。

但是,目前如果登錄成功,頁面仍然停留在只有空白頁的/Login,而不是重定向到/Home

登錄成功後,如何重定向到/Home

我是使用Servlet和Eclipse的新手。我剛開始學習J2EE和Eclipse。仍在探索。

  • 編輯(S):
  • 我改變了forward()sendRedirect()println()。當我使用錯誤的用戶名和密碼時,打印出「失敗」。但是當我使用正確的細節時,沒有打印出來。

回答

0

請勿使用sendRedirect() - forward()更合適,因爲您將請求重定向到同一臺服務器上(使用相對路徑)。如果您堅持使用sendRedirect() - 請使用拉URL。

+0

我是使用Servlet的新手。以前,我正在將這些請求指向'jsp',而不是'Servlet'。我不知道爲什麼頁面不顯示,即使我有'index.jsp'。我嘗試過使用'forward()'和'sendRedirect()',但兩者都指向空白頁,使用相同的目錄'/ Login'而不是'/ Home'。 – Chin 2014-08-31 05:37:12

+0

@Chin'forward()'不會更改url(但您可以嗅探瀏覽器並查看正在進行的調用)。空白頁面可能是'/ home'上發生的某種錯誤 - 但由於您沒有發佈該頁面的代碼,因此很難說出可能導致該行爲的原因。 – alfasin 2014-08-31 07:10:16

0

爲什麼你需要的是absolutePath的事情,如果您想要在web.xml或者註釋這種簡單的線條來重定向應做的工作

RequestDispatcher requestDispatcher=servletContext.getRequestDispatcher("/Home"); 
requestDispatcher.forward(request, response); 

的servlet的URL映射或本

response.sendRedirect("/Home"); 
+0

我編輯了一下代碼。爲什麼「成功」不打印出來,但可以打印出「失敗」? – Chin 2014-08-31 05:53:31

+0

你有沒有得到任何異常嘗試使用e.printStackTrace()打印異常; – SparkOn 2014-08-31 05:55:19

+0

嗯......我不知道該如何解釋。但是沒有'SQLException'和'Exception'。但我重新啓動服務器仍然是一樣的。我重新啓動Eclipse,也沒有錯誤。 – Chin 2014-08-31 06:15:25