當我得到空指針異常時,我正在檢查ServletContext
的用法。我不明白爲什麼我會得到這個異常。使用ServletContext時發生java.lang.NullPointerException
我已經從一個類中設置了context
對象中的屬性,然後嘗試使用getAttribute(...)
從第二個類中檢索該屬性。
package ServletContext; // servlet1
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class servlet1 extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
LinkedList list = new LinkedList();
list.add("suhail");
ServletContext servletContext = getServletContext();
servletContext.setAttribute("name", list);
}
}
package ServletContext; // servlet2
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class servlet2 extends HttpServlet {
public void doGet(HttpServletRequest request , HttpServletResponse response) throws IOException,ServletException {
LinkedList list2 = new LinkedList();
ServletContext context = getServletContext();
list2 = (LinkedList)context.getAttribute("name");
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
writer.println(list2.pop()); //**15th statement**
}
}
例外是:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error() that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
ServletContext.servlet2.doGet(servlet2.java:15)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
音符的根本原因的完整棧跟蹤可用在的Apache Tomcat/7.0.11日誌。
爲什麼我得到這個異常? list
應servlet2初始化
'servlet2.java:15':那是哪一行? – Thilo 2012-02-04 08:51:30
您確定要將列表放入servlet上下文嗎?不在會話或請求當前用戶? – Thilo 2012-02-04 08:52:57
@ Thilo試圖彈出項目的語句_(在servlet2中爲第15個)_ – 2012-02-04 08:54:35