2011-03-15 14 views
2

它是一個很好的做法/安全臨時存儲的HttpServletRequestHttpServletResponse的作爲的HttpServlet(見下文)的兩個字段?如果不是,爲什麼?存儲的HttpServletResponse和HttpServletRequest的作爲兩個字段的HttpServlet

import java.io.IOException;  
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

public class Test extends HttpServlet 
    { 
    private HttpServletRequest req; 
    private HttpServletResponse resp; 
    @Override 
    protected void doPost(
      HttpServletRequest req, 
      HttpServletResponse resp 
      ) 
      throws ServletException, IOException 
     { 
     try 
      { 
      this.req=req; 
      this.resp=resp; 
      do1(); 
      do2(); 
      } 
     finally 
      { 
      this.req=null; 
      this.resp=null; 
      } 
     } 

    private void do1() throws ServletException, IOException 
     { 
     //use req resp 
     } 
    private void do2() throws ServletException, IOException 
     { 
     //use req resp 
     } 
    } 

,或者我應該調用類似:

do1(req,resp); 
do2(req,resp); 

回答

8

它是一個很好的做法/安全的臨時存儲HttpServletRequest和HttpServletResponse的作爲的HttpServlet的兩個領域(見下文)?

不!

如果不是,爲什麼?

因爲servlets 必須是線程安全的。多個線程將同時通過該servlet對象。如果您將請求/響應存儲在字段中,則線程安全性將退出窗口。

不要試圖採取這種快捷方式只是爲了避免參數傳遞的視覺不愉快。

如果您確實必須避免參數,請將請求/響應存儲在java.lang.ThreadLocal字段中。這仍然是不好的做法,但至少現在它會是線程安全的。

相關問題