2013-07-25 47 views
1

我有這種情況:在重新提交相同請求時將請求屬性設置爲空

我需要將附件上載到服務器。我有一個jsp pageservlet它處理我的請求。在我上傳文件之前,我需要檢查重複的文件名,以便在不通知用戶的情況下替換文件。因此,在我的servlet中,我正在執行相應的檢查並將request attribute設置爲true,以便當我forward the request to the jsp page並查看該屬性設置爲true時,我會向用戶顯示一個對話框(使用jquery),以便用戶選擇要採取的行動(保持兩者,覆蓋,取消)。

我唯一擔心的是,當頁面刷新時,即same request is submitted,屬性設置爲true後,attribute remains true,因此刷新我得到我的對話框加載。當然,我不希望這發生。

有什麼可以幫助我解決這個問題嗎?這是我的代碼。

UploadFile.java - 我的servlet

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

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

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, java.io.IOException 
{ 
    request.setAttribute("duplicate", null); 

    if (!isDuplicate(file)){ 
     // .. handle uploading 
    } 
    else 
    { 
     // if duplicate 
     request.setAttribute("duplicate", "true"); 

     ServletContext context = getServletContext(); 
     RequestDispatcher dispatcher = context.getRequestDispatcher("/ticketsform.jsp"); 
     dispatcher.forward(request, response); 
    } 

    response.sendRedirect("ticketform.jsp"); 
} 

ticketform.jsp

<% 
    String isDuplicate = (String)request.getAttribute("duplicate"); 

    if (isDuplicate != null) 
    { %> 
     <script type="text/javascript"> 
      duplicateFilesOption(); // call js function to display dialog 
     </script> 
<% } %> 

感謝提前任何幫助:)

+0

isDuplicate正在返回良好結果。複製時爲true,否則爲false。在頁面刷新時,如果最後一個請求是重複文件,它仍然是真的。 – Bernice

+0

你可以把一些隱藏的字段,可以dynamiclly更改通過javascript/jquery isDuplicate。 –

+0

設置緩存標題(請參閱melt321),但我會將文件名的Ajax文章發送到servlet進行驗證,然後完整的文章應該可以做到這一點。 –

回答

0

您可以添加以下到您的JSP。

這會告訴瀏覽器重新發送請求,而不是重新顯示結果。

<head> 
<meta HTTP-EQUIV=Expires CONTENT="0"> 
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache"> 
<head> 
+0

嘗試過,並沒有做任何區別。感謝嘗試,雖然 – Bernice

0

在ticketform.jsp結束時,請刪除屬性。

request.removeAttribute("attribute_name"); 

所以在從請求中獲得價值之後,它首先會被刪除。

+0

嘗試過,但也沒有工作!還在刷新加載對話框 – Bernice

+0

好的,我認爲刷新時的url會再次引發servlet和設置請求屬性。提交動作之前和之後請檢查頁面的網址。最好在servlet中使用response.sendRedirect()方法,並在HttpSession中放置標誌,然後從jsp頁面的第一個會話中獲取值,最後刪除會話值。 – pikrut

+0

我認爲它不會再次訪問servlet會影響到這一點,因爲如果它正在重新提交,那麼就存在set屬性的空語句。你認爲如果我使用Ajax而不是重定向,這個問題會解決嗎? – Bernice