Search code examples
javatomcatservletstomcat6servlet-filters

set up context variable in tomcat


I am having problem setting up tomcat context variable. I have tried:

  1. in web.xml in root folder(note: it's not the one in conf folder) I tried adding context-param, not work, this did not change anything, the context variable is still null

    <context-param>
        <param-name>testname</param-name>
        <param-value>testvalue</param-value>
    </context-param>
    
  2. using servlet getServletContext.setAttribute("test","ok") to set variable, it does not work either, the variable just stay null all the time.

  3. i have tried to add crossContext=true in server.xml (even though i only have one webapp), it does not work.

so any suggestions?

Thanks


Solution

  • You need to add the context parameter to the /WEB-INF/web.xml of your webapp, not one "in root folder" wherever that is.

    <context-param>
        <param-name>testname</param-name>
        <param-value>testvalue</param-value>
    </context-param>
    

    You need to get it by ServletContext#getInitParameter():

    String testname = getServletContext().getInitParameter("testname");
    System.out.println(testname); // testvalue
    

    The ServletContext#set/getAttribute() sets/gets attributes in the application scope. They are not related to context parameters.