简体   繁体   中英

Is this the right way to have “global” parameters for my servlets?

If I have:

  <context-param>
    <param-name>SomeParam</param-name>
    <param-value>SomeValue</param-value>
  </context-param>

in my web.xml , is this the servlet way of specifying options ( like in the way a config file is used ) , or am I doing something wrong? I know about init-param that can be specified for a servlet, but I'd like o make sure some values are the same for all the servlets.

The <context-param> is to define context-wide initialization parameters which is available to all servlets. Inside a servlet you can obtain them by ServletContext#getInitParameter() , eg

public void init() {
    String someParam = getServletContext().getInitParameter("someParam");
}

That's the right way to have a "global" parameter for all your servlets. But you can also define servlet-specific initialization parameters inside <servlet> as follows:

<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>com.example.MyServlet</servlet-class>
    <init-param>
        <param-name>someParam</param-name>
        <param-value>someValue</param-value>
    </init-param>
</servlet>

You can obtain them by the inherited GenericServlet#getInitParameter() method. Eg

public void init() {
    String someParam = getInitParameter("someParam");
}

是的,您是对的。继续进行即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM