My JSP pages need to display different information depending on which environment they're in (dev, production, sandbox, etc). I want to have a properties file for each of these environments that contain all the parameters they might need. How can I reference the properties from this file in a JSP page?
My thoughts are:
- Have a servlet feed the properties in the form of a model object to all JSP pages so I can reference them like ${properties.propertyName}
- Somehow reference this property file in the web.xml, then maybe I call something like ${context.properties.propertyName}?
- Instead of a properties file, list parameters in web.xml and reference those in the JSP pages. Not sure how to do this, but I'd very much prefer a simpler properties file.
UPDATE - I should've mentioned I'm using Spring 3.0 and Spring webmvc. So if there's some best practices way to do this using Spring, that's ideal!
You can load the properties using
java.util.Properties
(or commons-configuration) in aServletContextListener
'scontextInitialized(..)
method.register the listener with
<listener>
in web.xmlYou then store the
Properties
into theServletContext
(you can get it from the event) (ctx.setAttribute("properties", properties)
then access the properties using
${applicationScope.properties.propName}
(as BalusC noted,applicationScope
is optional)Update:
Initially I thought spring had some ready-to-use facility for that, but it turns out it's not exactly the case. You have two options:
this article explains something similar to my suggestion above, but using spring's
PropertyPlaceholderConfigurer
this answer and this answer allow you to expose all your beans, including a
PropertyPlaceholderConfigurer
to the servlet context.After doing the above, your properties will be available to your JSP files.
If you initialize using a SessionContextListener (this is not valid code, but the point is made):
If you initialize using a Servlet (assuming you extend GenericServlet):
Without going into the discussion of where is the best location to store environment-specific data (hint: certainly not property files), I would stick to the basics:
JSP pages render data; they don't fetch it. If at some point, later on, you end up getting properties from somewhere else other than a property file - your JSP, assuming your application is well-designed - should not change.
Therefore, the first approach you mentioned makes sense (assuming, again, that you'd like to stick with environment-specific information being read from Property files).
I had the same problem. I was able to solve it by exposing the config file in my webmvc-config.xml file using a Resource Bundle:
Then I was able to use it in my JSPs using a <spring:message /> tag: