2013-03-31 25 views
1

在servlet,我想分享的init之間的可變和的doGet如何在init和doget之間共享變量?

我想知道我是否應該使用靜態或只是正常

(static?) int small; 

init() 
{ 
    small = 5:  
} 

doGet(final HttpServletRequest request, final HttpServletResponse response) { 
    small 
} 
+0

你想'small'是該servlet的所有用戶之間共享?或者你想爲每個請求提供一個'small'的實例嗎? – Todd

+0

我想確保我理解這兩種情況 –

+0

servlet規範說,在初次請求之前調用'init'方法。所有請求都共享同一個servlet實例。如果變量是靜態的,它應該沒有什麼區別,除非你在web.xml中聲明瞭多次servlet –

回答

0

不要緊,聲明這個變量。 Java Servlet規範將創建一個servlet實例,並調用init一次。無論您是將該值置於靜態變量還是非靜態變量中,它都將可用於在該servlet上執行doGet請求的所有線程。

我傾向於使用靜態,因爲它幫助程序員清楚地知道所有調用都有一個副本,而靜態對於給定的請求顯然不是唯一的。此外,如果您有任何需要,靜態代碼的其他部分(servlet類本身之外)更容易訪問。

0

這取決於你想如何更好地設計你的代碼。我會建議使用非靜態的,因爲考慮用多個子類來擴展這個類。

將它作爲成員變量將允許您爲不同的子類使用不同的值。而靜態你不能。

public class Superclass { 

protected static String sVariable = "static"; 
protected String mVariable = "static"; 

public void init() { 
} 


    public void print(){ 
    System.out.println(this.getClass().getName() + ":sVariable" + sVariable); 
    System.out.println(this.getClass().getName() + ":mVariable" + mVariable); 
    } 
} 

public class SubClass extends Superclass { 

public void init() { 
    sVariable = "subClassSVariable"; 
    mVariable = "subClassMVariable"; 
} 


public static void main(String a[]){ 
    Superclass superC = new Superclass(); 
    SubClass subC = new SubClass(); 

    superC.init(); 
    subC.init(); 

    superC.print(); 
    subC.print(); 
    } 
} 

以上代碼的輸出是:

com.ramesh.Superclass:sVariablesubClassSVariable 
com.ramesh.Superclass:mVariablestatic 
com.ramesh.SubClass:sVariablesubClassSVariable 
com.ramesh.SubClass:mVariablesubClassMVariable