2017-06-30 56 views
-2

訪問「initparam」我學習Servlet和我創建了一個樣本sevlet並創建了一個名爲使用註釋「消息」 initparam。我試圖訪問doGet()方法中的參數,但獲得nullPointerException。可能是什麼問題?下面的代碼給出:不能在Servlet的

@WebServlet(
     description = "demo for in it method", 
     urlPatterns = { "/" }, 
     initParams = { 
       @WebInitParam(name = "Message", value = "this is in it param", description = "this is in it param description") 
     }) 
public class DemoinitMethod extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    String msg = ""; 

    /** 
    * @see HttpServlet#HttpServlet() 
    */ 
    public DemoinitMethod() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    /** 
    * @see Servlet#init(ServletConfig) 
    */ 
    public void init(ServletConfig config) throws ServletException { 
     msg = "Message from in it method."; 
    } 

    /** 
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
    */ 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     PrintWriter out = response.getWriter(); 
     out.println(msg); 

     String msg2 = getInitParameter("Message"); 
     out.println("</br>"+msg2); 
    } 

    /** 
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
    */ 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
     doGet(request, response); 
    } 

} 

回答

1

您重新定義了init方法在servlet,所以你需要調用初始化 GenericServlet類類的方法。

例如:

public void init(ServletConfig config) throws ServletException { 
     super.init(config); 

     msg = "Message from in it method."; 
    } 

爲了節省您不必這樣做,GenericServlet類提供了另一種init方法沒有參數,從而可以覆蓋一個不帶參數。

public void init(){ 
msg = "Message from in it method."; 
} 

init wihout參數將由GenericServlet中的一個調用。

Herer是init方法的GenericServlet類代碼:

public void init(ServletConfig config) throws ServletException { 
this.config = config; 
this.init(); 
} 
+0

我得到了你的觀點。但是我仍然沒有得到如何在doGet()方法中打印param'message'的值,這個方法是由我在servlet開頭的註釋中創建的。 –

+0

'的getInitParameter(「信息」)'是正確的,你的空指針異常可能是由於因爲你overrided init方法,其未初始化的變量的ServletConfig。只要按照說明更改您的代碼,您應該沒問題。 –

+0

哇。那很整齊。我試過了,它工作。萬分感謝! –