-2

我正在学习 servlet,我创建了一个示例 sevlet,并使用注释创建了一个名为“消息”的 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);
    }

}
4

1 回答 1

1

您已经在 servlet 中重新定义了 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.";
}

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

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

public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
于 2017-06-30T13:37:41.627 回答