2012-05-02 35 views
0

我試圖創建一個Java控制器servlet來將用戶登出會話。 我知道有兩種方法,一種是使用sendRedirect,另一種是RequestDispatcher。在我的情況下,我想將它們發送到域外的頁面,這(對我有限的Java知識)要求我使用sendRedirect。sendRedirect不重定向

但是,我收到一個錯誤302並且頁面沒有被重定向。我嘗試過一個教程版本,它的工作原理,但是當我在我的Servlet中實現它時,它會返回錯誤信息並且不會重定向。

我希望有人能指出我正確的方向。

我使用的代碼如下。我使用NetBeans模板:


protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 
    PrintWriter out = response.getWriter(); 
    try { 
     HttpSession session = request.getSession(false); 
     if (session == null) { 
      System.out.println("Invalid"); 
      response.sendRedirect("http://www.google.com"); 
      return; 
     } else { 
      System.out.println("Invalidated"); 

      session.invalidate(); 
      response.sendRedirect("http://www.google.com"); 
      return; 
      /* 
      String url = "/logout.jsp"; 

      ServletContext sc = getServletContext(); 
      RequestDispatcher rd = sc.getRequestDispatcher(url); 
      rd.include(request, response); 

      */ 
     } 
     /* TODO output your page here 
     out.println("<html>"); 
     out.println("<head>"); 
     out.println("<title>Servlet LogOut</title>"); 
     out.println("</head>"); 
     out.println("<body>"); 
     out.println("<h1>Servlet LogOut at " + request.getContextPath() + "</h1>"); 
     out.println("</body>"); 
     out.println("</html>"); 
     */ 
    } finally {    
     out.close(); 
    } 
} 

編輯:我打電話通過<a href>標籤的servlet。 Servlet名稱是LogOut.java。

 <div data-role="header" data-position="fixed"> 
      <h1>Menu</h1> 
      <a href="LogOut" data-theme="i">Log Out</a> 
     </div> 

doGet和doPost調用processRequest。

@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    processRequest(request, response); 
} 

/** 
* Handles the HTTP <code>POST</code> method. 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    processRequest(request, response); 
} 
+2

'302'是不是一個錯誤;這是一個狀態碼,告訴瀏覽器重定向。 – skaffman

+0

嗨skaffman,感謝您的快速回復。我不確定我自己,因爲它基於使用螢火蟲搜索到的內容。但是,阻止瀏覽器重定向的是什麼?這可能是由於我在jsp頁面中使用jQueryMobile嗎? – Rax

回答

0

響應的標準重定向是您的應用程序中的參考。 爲了解決這個問題,我創建了元數據刷新一個簡單的HTML頁面的外部頁面: http://www.w3schools.com/tags/tag_meta.asp
例子:
<meta HTTP-EQUIV="refresh" CONTENT="2; URL=http://www.google.be;">

確保一個簡單的超鏈接來訪問外部頁面應該自動轉發失敗。

一旦通過測試,從servlet響應重定向到我自己的轉頁,瞧...

+0

嗨,Jan,這是否意味着無法在不使用額外的HTML頁面的情況下立即從servlet重定向?但是當我按照教程時,它運行良好。我不確定爲什麼只有在我嘗試在我自己的servlet中實現它時纔會發生這種情況。 – Rax

+1

'response.sendRedirect'是正確的方法,它應該工作。我懷疑在doPost()或doGet()中可能會有其他代碼導致問題。 提供您正在調用'processRequest'的代碼。 –

+0

嗨哈迪克,我已經添加了該信息所要求的信息。希望早日收到你的消息。 – Rax