[英]java.lang.NullPointerException while using ServletContext
I was examining the use of ServletContext
when i got the null pointer exception. 当我得到空指针异常时,我正在研究
ServletContext
的使用。 I don't understand why do i get this exception. 我不明白为什么我会得到这个例外。
I have set the attribute in the context
object from one class and then try to retrieve that from the second class using getAttribute(...)
. 我已经在一个类的
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**
}
}
Exception is : 例外是:
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)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.11 logs. note注意在Apache Tomcat / 7.0.11日志中可以找到根本原因的完整堆栈跟踪。
Why am i getting this exception ? 为什么我会收到此例外?
list
should be initialized in servlet2 list
应在servlet2中初始化
list2
is null
there - you can't invoke methods on null
. list2
是null
在那里-你不能调用上的方法null
。 Perhaps you still haven't put the list in the servlet context? 也许您还没有将列表放在servlet上下文中? A null-check (
if (list != null)
) would fix the exception, but make sure you are properly putting the list in the context before you invoke the 2nd servlet. 空检查(
if (list != null)
)可以解决该异常,但是在调用第二个servlet 之前,请确保将列表正确放入上下文中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.