Discussions

Web tier: servlets, JSP, Web frameworks: how to access object in application scope from servlet?

  1. application.setAttribute("a","a");
    how do I retrieve this "a" from the servlet?
    thanks
  2. you need to use the ServletContext's getAttribute function
  3. you must use a cast to the object depending on what you passed.

    application.setAttribute("a","a");

    so the first "a" is your key, the second "a" is a String object.

    therefore,

    String s = (String)application.getAttribute("a");

  4. this can only be work on jsp not in servlet
  5. the servlet solution is the aforementioned ServletContext...
    here's some snippets:

    Servlet A
    ---------------------------------------
    Vector v = new Vector();

    ServletContext sc = getServletConfig().getServletContext();
    sc.setAttribute("abc", v);
    ---------------------------------------

    Servlet B
    ---------------------------------------
    ServletContext sc = getServletConfig().getServletContext();
    Vector v = (Vector)sc.getAttribute("abc");
    ---------------------------------------


    JSP's application variable is just the ServletContext object