-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);
}
}
我得到了你的觀點。但是我仍然沒有得到如何在doGet()方法中打印param'message'的值,這個方法是由我在servlet開頭的註釋中創建的。 –
'的getInitParameter(「信息」)'是正確的,你的空指針異常可能是由於因爲你overrided init方法,其未初始化的變量的ServletConfig。只要按照說明更改您的代碼,您應該沒問題。 –
哇。那很整齊。我試過了,它工作。萬分感謝! –