在Tomcat中设置上下文变量

3

我在设置Tomcat上下文变量时遇到了问题。 我尝试过:

  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.

所以你有什么建议吗?谢谢。

基本上,我想改变上下文变量的值,稍后另一个servlet可以使用它。 - ikel
功能需求是什么?设置一个变量,使其可以被部署在同一Tomcat服务器上的所有Web应用程序访问? - BalusC
是的,这个变量将需要被同一服务器上的其他过滤器访问。 - ikel
1个回答

4
您需要将上下文参数添加到您的Web应用程序的/WEB-INF/web.xml中,而不是任何“在根文件夹中”的位置。
<context-param>
    <param-name>testname</param-name>
    <param-value>testvalue</param-value>
</context-param>

您需要通过ServletContext#getInitParameter()来获取它:

String testname = getServletContext().getInitParameter("testname");
System.out.println(testname); // testvalue
ServletContext#set/getAttribute() 是在应用程序范围内设置/获取属性的方法。它们与上下文参数无关。请注意保留HTML标记。

抱歉,我应该更清楚一些,这个变量被同一应用程序中的其他人在同一台服务器上访问。目前,我在服务器上只有一个Web应用程序。此外,我没有权限在服务器上运行命令(它是共享托管服务器),因此环境变量可能不是一个好主意。 - ikel
难怪我总是得到 null 值,因为我使用的是 getServletContext().getAttribute("test")。我原以为只有在 <servlet> 中指定了 <init-param> 时才会使用 getInitParameter("test")。现在我明白了。 - ikel
上下文属性与上下文参数不同。Servlet初始化参数仅可通过ServletConfig或继承的GenericServlet#getInitParameter()获得。至于设置值,请猜测...(提示:阅读javadoc)。 - BalusC
要了解属性是什么以及如何使用它们,请花些时间阅读https://dev59.com/GnA75IYBdhLWcg3wy8Qi,这将总体上有所启发。 - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接