使用ServletContext时的java.lang.NullPointerException

时间:2012-02-04 08:46:57

标签: java java-ee servlets

当我得到空指针异常时,我正在研究ServletContext的使用。我不明白为什么我会得到这个例外。

我在一个类的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中初始化

1 个答案:

答案 0 :(得分:0)

list2在那里null - 您无法在null上调用方法。也许您还没有将列表放在servlet上下文中?空检查(if (list != null))将修复异常,但请确保在调用第二个servlet之前正确地将列表放在上下文中。