无法在 Servlet 中访问 'initparam'

Not able to access 'initparam' in Servlet

我正在学习 servlet,我创建了一个示例 sevlet 并使用注释创建了一个名为 'message' 的 initparam。我试图在 doGet() 方法中访问该参数但得到 nullPointerException。可能是什么问题?代码如下:

@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);
    }

}

您已经在您的 servlet 中重新定义了 init 方法,因此您需要调用 GenericServlet class.

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

没有争论的init将被GenericServlet中的那个调用。

下面是GenericServlet中init方法的代码:

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