Java Servlets - Storing a list of values in web.xml (multiple param-value's for single param-name)
Asked Answered
P

5

35

I'm creating a servlet that needs to load configuration information. Part of the configuration information I need is a list of Strings (specifically, a list of hostnames and/or URLs).

I was hoping to store this information in my servlet's web.xml file (so I don't have to write my own parser) as either a context-param or init-param; essentially multiple param-value's for a single param-name.

Example of what I would like:

<context-param>
    <param-name>validHosts</param-name>
    <param-value>example1.com</param-value>
    <param-value>example2.com</param-value>
    <param-value>example3.com</param-value>
</context-param>

My initial research seems to indicate this is not possible--that there can only be a single param-value for any param-name (within either context-param or init-param).

I know I could just use a delimited list within a single param-value, but is that really my only option if I still want to use web.xml? Should I just stop whining and write my own config file parser?

Padus answered 11/4, 2012 at 18:0 Comment(0)
B
47

Servlet spec says that you can have only one value for any context parameter. So, you are left with going with delimited list only.

<context-param>
  <param-name>validHosts</param-name>
  <param-value>example1.com,example2.com,.....</param-value>
</context-param>
Burress answered 11/4, 2012 at 18:30 Comment(0)
M
22

Put each param on its own line. I did the following recently and it works fine:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-beans.xml
        /WEB-INF/security-config.xml    
    </param-value>
</context-param>
Michal answered 11/4, 2012 at 18:41 Comment(2)
So I assume you just split with a newline character and trimmed whitespace? This would definitely make it more readable.Padus
This only works because spring splits the values for you in the ContextLoaderListener. From their documentation: Set the config locations for this application context in init-param style, i.e. with distinct locations separated by commas, semicolons or whitespace.Dreyfus
K
14

Yes, just use delimiters (as no other options available for this):

<context-param>
    <param-name>validHosts</param-name>
    <param-value>example1.com,example2.com,example3.com</param-value>
</context-param>



then simply
String[] validHosts = param.split(","); // not really much to do
Kershaw answered 11/4, 2012 at 18:17 Comment(0)
V
-1

You should use ; to separate them in param-value tag like:

<context-param>
  <param-name>validHosts</param-name>
  <param-value>example1.com;example2.com;.....</param-value>
</context-param>
Vienna answered 25/8, 2019 at 10:32 Comment(0)
R
-3

This works for me. The right delimiter to use is the ;

Rothenberg answered 14/2, 2022 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.