3

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

Marko Topolnik
  • 179,046
  • 25
  • 276
  • 399
ikel
  • 1,530
  • 5
  • 24
  • 51
  • basically, i want change value of context variable and later one another servlet can use it – ikel Feb 14 '12 at 00:04
  • What's the functional requirement? Setting up a variable which is accessible by all web applications deployed on the very same Tomcat server? – BalusC Feb 14 '12 at 00:10
  • yes, the variable will have to be accessed by other filters on same server – ikel Feb 14 '12 at 00:22

1 Answers1

4

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.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • sorry, i should be more clear on that, this variable is accessed by others on same server within one application. currently, i only have one webapp on server. in addition, i dont have access to run command on server(it's a shared hosting server), so environment variable might not be a good idea. – ikel Feb 14 '12 at 01:00
  • no wonder i always got null, because i used getServletContext().getAttribute("test"). I thought getInitParameter("test") is used only when is specified in , now i got it – ikel Feb 14 '12 at 01:52
  • Context attributes are not the same as context parameters. The servlet init parameters are only available by `ServletConfig` or the inherited `GenericServlet#getInitParameter()`. As to setting the value, do a guess... (hint: read javadoc). – BalusC Feb 14 '12 at 01:56
  • To learn about what attributes are and how they are to be used, take some time to read http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading, which should be enlightening in general. – BalusC Feb 14 '12 at 01:57