I was examining the use of ServletContext when i got the null pointer exception. 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(...).
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.
Why am i getting this exception ? list should be initialized in servlet2
list2isnullthere – you can’t invoke methods onnull. Perhaps you still haven’t put the list in the servlet context? 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.