2014-10-01 75 views
-1

如何获取JSF生命周期之外和Servlet之外的web.xml参数? 我能找到的所有东西都与servlet,jsf请求或者像Spring或Struts这样的框架的特定方法有关。来自非servlet的web.xml参数,外部JSF生命周期

在纯Java EE中难以从web.xml中获取配置吗?

在实践

getServletContext().getInitParameter("ContextParam"); 
FacesContext.getCurrentInstance().getExternalContext().getInitParameterMap(); 

都无法使用。

+0

在什么环境下你想要做到这一点? – kolossus 2014-10-02 03:00:29

回答

0

创建ServletContextListener和一类,为exampel AppContext一些staitc领域

class AppContext { 
    static String param = null; 

    public satitc void setParam(String p) { 
     param = p; 
    } 

    public satitc getParam() { 
     return param; 
    } 
} 

在该方法中contextInitialized读取参数SND它们设置为您AppContext

@Override 
public void contextInitialized(ServletContextEvent arg0) { 
    AppContext.setParam(arg0.getServletConext().getInitParameter("ContextParam")); 
} 

使用方法AppContext#getParam()哪里你要。

Here a small tutorial on this topic

0

当你的应用程序加载,你可以从你的初始化参数得到这个信息,并保存使用的ServletContextListener,这样的事情在其他时间使用:

public class TestListener implements ServletContextListener { 

    @Override 
    public void contextInitialized(ServletContextEvent servletContextEvent) { 
     String yourVariable = servletContextEvent.getServletContext().getInitParameter("yourParameter"); 
     //Some code.. 
    } 
} 

在web.xml定义这个监听器:

<web-app ...> 
    <listener> 
    <listener-class> 
      com.fullanem.TestListener 
     </listener-class> 
    </listener> 
</web-app> 

在web.xml中定义的参数太多:

<context-param> 
    <description>This is a context parameter example</description> 
    <param-name>yourParameter</param-name> 
    <param-value>Your value</param-value> 
    </context-param> 

所以你将它存储在你想要的地方,作为属性,全局变量或任何地方。