JSP/servlet从属性文件中读取参数? [英] JSP/servlet read parameters from properties file?

查看:129
本文介绍了JSP/servlet从属性文件中读取参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSP页面需要根据其所处的环境(开发,生产,沙箱等)显示不同的信息.我想为这些环境中的每个环境创建一个属性文件,其中包含它们可能需要的所有参数.如何在JSP页面中引用此文件中的属性?

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?

我的想法是:

  • 让servlet以模型对象的形式将属性提供给所有JSP页面,以便我可以像$ {properties.propertyName}一样引用它们.
  • 以某种方式在web.xml中引用此属性文件,然后也许我调用$ {context.properties.propertyName}之类的东西?
  • 在web.xml中列出参数,并在JSP页面中引用这些参数,而不是属性文件.不确定如何执行此操作,但是我非常希望使用一个更简单的属性文件.

更新 -我应该提到我正在使用Spring 3.0和Spring webmvc.因此,如果有一些使用Spring的最佳实践方法,那是理想的选择!

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!

推荐答案

  • 您可以使用java.util.Properties(或公共配置)加载属性.在ServletContextListenercontextInitialized(..)方法中.

    • You can load the properties using java.util.Properties (or commons-configuration) in a ServletContextListener's contextInitialized(..) method.

      在web.xml中的<listener>中注册侦听器

      register the listener with <listener> in web.xml

      然后将Properties存储到ServletContext中(可以从事件中获取它)(ctx.setAttribute("properties", properties)

      You then store the Properties into the ServletContext (you can get it from the event) (ctx.setAttribute("properties", properties)

      然后使用${applicationScope.properties.propName}访问属性(如BalusC所述,applicationScope是可选的)

      then access the properties using ${applicationScope.properties.propName} (as BalusC noted, applicationScope is optional)

      更新:

      最初,我认为spring可以使用一些现成的工具,但事实并非如此.您有两种选择:

      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:

      • 本文解释了与我上面的建议类似的内容,但是使用了spring的PropertyPlaceholderConfigurer

      • this article explains something similar to my suggestion above, but using spring's PropertyPlaceholderConfigurer

      此答案此答案可让您公开所有bean ,包括servlet上下文的PropertyPlaceholderConfigurer.

      this answer and this answer allow you to expose all your beans, including a PropertyPlaceholderConfigurer to the servlet context.

      这篇关于JSP/servlet从属性文件中读取参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆