getServletContext Issue

Discussions

General J2EE: getServletContext Issue

  1. getServletContext Issue (9 messages)

    Hi,

    I have a class the I instantiate in a JSP. This class use the getServletContext() of the HttpServlet class to get a context variable. I get a NullPointerException on the JSP when I try to instantiate this class in the JSP. I know it's the getServletContext() that's causing the problem because it works when I comment it out.

    Does anyone have any idea why this is happening?

    Thanks for the help,

    -r

    Threaded Messages (9)

  2. getServletContext Issue[ Go to top ]

    Two suggestion:

    1) Make sure the name in the context.getAttribute() matches the name used for context.setAttribute()

    2) In the JSP, try using the implicit application variable (which should be the same as your ServletContext).
  3. getServletContext Issue[ Go to top ]

    Hi Paul,

    Thanks for the reply. Yes the names match on the set and get Attributes. As for you 2nd suggestion please see my previous post on this thread.

    -Ray
  4. getServletContext Issue[ Go to top ]

    Simple. You cannot do that. getServletContext() can be used only when your current class inherits from servletconfig, else you will get null. The only way would be to pass the config as a param. when you instantiate it and then call getServletContext on that. Or pass the context as param when you instantiate.


    Read spec for more details please, when you get time.

    -Sanjay.
  5. getServletContext Issue[ Go to top ]

    Thanks for the reply.

    I've simplified the classes involved to help with troubleshooting. There are 3 file involved: JSP, Action class, and a Listener class:

    JSP:
    <%
    SearchAction searchAction=new SearchAction();
    String x=searchAction.getStringFromContext();
    out.println(x);
    %>

    ACTION CLASS (STRUTS):
    public class SearchAction extends Action {
      public ActionForward execute(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
                                        throws Exception {

            String forwardCmd="";
            return(mapping.findForward(forwardCmd));
        }

        public String getStringFromContext() {
            return (String)this.getServlet().getServletContext().getAttribute("DAOx");
        }
    }

    LISTENER CLASS (starts up when tomcat is started via the listener tag in web.xml):
    package com.rf3labs.framework.listener;

    import javax.servlet.ServletContextListener;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContext;

    import com.rf3labs.framework.dao.*;
    //import com.rf3labs.framework.xmlparser.*;
    import com.rf3labs.framework.connectionpool.*;
    import com.rf3labs.framework.*;

    public class DAOListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    // Retrieve the parameters from web.xml
    String driverName = context.getInitParameter("driverName");
    String dbUrl = context.getInitParameter("dbUrl");
    String userId = context.getInitParameter("userId");
    String passWord = context.getInitParameter("passWord");

    try {
    //DAO dao = new DAO(driverName, dbUrl, userId, passWord);
    //context.setAttribute("DAO", dao);
                    context.setAttribute("DAOx", "this is from context");

    log(context, "Context Initialized: " + new java.util.Date());
    }
    catch (Exception exc) {
    log(context, exc.getMessage());
    exc.printStackTrace();
    }
    }

    public void contextDestroyed(ServletContextEvent event) {
    log(context, "Context Destroyed: " + new java.util.Date());
    }

    private void log(ServletContext context, Object message) {
    String contextName = context.getServletContextName();
    context.log(contextName + ": " + message.toString()); // server's event log
    System.out.println(contextName + ": " + message); // stdout
    }
    }

    I get a nullpointerexception when I access the servletcontext attribute in the
    SearchAction class via the JSP. When I access the servletcontext attribute directly from the JSP it works fine but now from another class (SearchAction).

    Thanks for you help.

    -Ray
  6. getServletContext Issue[ Go to top ]

    Looking your code, the problem is clear. In you JSP, you are creating a new Struts SearchAction:

    // In the JSP:
    SearchAction searchAction = new SearchAction();

    Since this action is created by your JSP code, it is not being initialized by Struts. Therefore it does not have a reference to the Struts servlet, which is why you are getting the NullPointerException here:

    this.getServlet().getServletContext() ...

    The solution is to invoke the ServletContext directly in your JSP via the implicit application object:

    <%
    SearchAction searchAction=new SearchAction();
    String x = (String) application.getAttribute("DAOx");
    out.println(x);
    %>

    This is no need to "pass" the ServletContext around, because it is effectively a global object, and every reference to the ServletContext for a given web application will be the same object.
  7. getServletContext Issue[ Go to top ]

    I need to get the context attribute from the SearchAction class since I'm using the Struts framework. Is there a way to get the context I need from the SearchAction?

    Thanks,

    -Ray
  8. getServletContext Issue[ Go to top ]

    The ServletContext of the SearchAction is the same ServletContext used by every JSP and Servlet in the web application. The ServletContext is not "Struts specific", it is part of the Servlet standard. Try what I suggested and see if it works.
  9. getServletContext Issue[ Go to top ]

    I need to get the context attribute from the SearchAction class since I'm using the Struts framework. Is there a way to get the context I need from the SearchAction?Thanks,-Ray
    As Paul said, ServletContext is a global one, you don't need to pass from Action class. I think your problem is how to pass a value from Action Class to JSP. One of the standard ways to do this is, By having an attribute and get & set methods in your form class, and assign the values from Action class to form class, like form.setMyValue("AAA");

    and from your jsp, you can use various Struts tags to display them.

    <bean:write name="formName" property="userId" />


    Hope this will help.
    Thanks,
    Senthil.
  10. getServletContext Issue[ Go to top ]

    Sanjay,

    Thanks for the reply. Unfortunately I would not be able to pass the ServletContext from the JSP since I'm using Struts. If you're familiar with Struts JSP pages have access to a FORM bean class that is populated by the ACTION class. I need to get the context attribute from the Action class.

    I've attached code snippets from my previous post.

    Thanks,

    -Ray