2017-06-30 7 views
-2

サーブレットを学習していて、サンプルのセブレットを作成し、注釈を使って 'message'というinitparamを作成しました。私はdoGet()メソッドでそのparamにアクセスしようとしていますが、nullPointerExceptionを取得しようとしています。何が問題なの?コードは以下のとおりである:サーブレットの 'initparam'にアクセスできない

@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 GenericServletからクラスのメソッドを呼び出す必要があるので、あなたは、サーブレットにinitメソッドを再定義しています。

例:

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."; 
} 

GenericServlet内の引数によって初期化されます。私はあなたのポイントを得た

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

HererはGenericServletからでinitメソッドのコードです。しかし、サーブレットの初めに注釈で私が作成したdoGet()メソッドで、paramの 'message'の値をどのように出力することができるのか、まだ分かりませんでした。 –

+0

'getInitParameter(" Message ")'が正しいです、あなたのnullpointer例外はおそらく、あなたがinitメソッドをオーバーライドしたために初期化されなかったServletConfig変数のためです。説明されているようにあなたのコードを変更するだけで大​​丈夫です。 –

+0

うわー。それはきちんとしていた。私は試して、それは働いた。ありがとう、トン! –

関連する問題