2012-11-30 24 views
6

我想重寫的init(ServletConfig類配置)method.My代碼:的Java Servlet的重寫的init(ServletConfig類配置)

public void init(ServletConfig config) throws ServletException { 
    ServletContext sc = getServletContext(); // ----- NullPointerException 
} 

這是給NullPointerException異常。

如果我修改爲:

public void init(ServletConfig config) throws ServletException { 
    ServletContext sc = config.getServletContext(); // ----- works fine 
} 

這工作得很好。 我知道我們應該重寫init()方法而不是init(ServletConfig config),但是
有人可以給我正確的理由說明爲什麼會發生這種情況嗎?

+1

你在哪裏發現*我們應該重寫init()方法而不是init(ServletConfig config)*? –

+0

我並不是說我們不能覆蓋init(ServletConfig config)方法,我們可以,但是我從init(ServletConfig config)方法內部調用init()方法,因此我們應該重寫init()方法。 –

+0

它看起來像你已經有你的答案。你還需要什麼? –

回答

19

比較文檔init(ServletConfig)

 
public void init(ServletConfig config)throws ServletException 
Called by the servlet container to indicate to a servlet that the servlet 
is being placed into service. 

See Servlet#init. This implementation stores the ServletConfig object 
it receives from the servlet container for later use. When overriding 
this form of the method, call super.init(config). 

和比較,與init()的文檔:

 
public void init() throws ServletException 
A convenience method which can be overridden so that there's no need to 
call super.init(config). 

Instead of overriding init(ServletConfig), simply override this method 
and it will be called by GenericServlet.init(ServletConfig config). The 
ServletConfig object can still be retrieved via getServletConfig(). 

當重寫init(ServletConfig),必須做的第一件事就是打電話:

super.init(config); 

如果你d o然後在你的方法中直接調用getServletContext()將不再導致NPE。

+0

意味着在調用super.init(config)之後,servlet將獲得對servletcontext的引用? –

+0

@RiteshKaushik是的,這就是它的意思。 –

1

因爲:

public void init(ServletConfig config) throws ServletException 
{ 
    ServletContext sc = getServletContext(); 
} 

你不調用super.init(ServletConfig)。因此,ServletConfig不存儲在servlet實例中,隨後對getServletConfig的調用將返回null。

2

這是因爲您要重寫方法不對機制 如果重寫

 public void init(ServletConfig config) throws ServletException { 
     super.init(config); 
      ServletContext sc = getServletContext(); 
    } 

而是覆蓋init(ServletConfig),只需重寫以下方法,它會通過GenericServlet.init(ServletConfig config)

public void init() throws ServletException { 
ServletContext sc = getServletContext(); 
} 
0

只要把被稱爲超級初始化(配置)在你的覆蓋方法的第一行

public void init(ServletConfig config) throws ServletException