2012-09-23 47 views
0

我想在应用程序启动时从ServletContext获取服务器URL(例如http://www.mywebapp.com/myapp),我通过在启动时调用一个bean方法(使用@Startup)并获取servlet上下文,在应用程序启动时获取服务器上下文路径

@Startup 
@Name("startupActions") 
@Scope(ScopeType.APPLICATION) 
public class StartupActionsBean implements StartupActions, 
Serializable { 

@Logger private Log log; 

/** 
* 
*/ 
private static final long serialVersionUID = 1L; 

@Create 
@Override 
public void create(){ 
    ServletContext sc = org.jboss.seam.contexts.ServletLifecycle.getServletContext(); 
    String context = sc.getContextPath(); 
    String serverInfo = sc.getServerInfo(); 
    log.debug("__________________START__________________"); 
    log.debug("Context Path: "+context); 
    log.debug("Server Info: "+serverInfo); 
} 

// Cleanup methods 
@Remove 
@BypassInterceptors 
@Override 
public void cleanUp(){} 
} 

这项工作确定,但ServletContext的路径是空白的,请参见下面的控制台输出..

18:52:54,165 DEBUG [uk.co.app.actions.startup.StartupActionsBean] __________________START__________________ 
18:52:54,165 DEBUG [uk.co.app.actions.startup.StartupActionsBean] Context Path: 
18:52:54,165 DEBUG [uk.co.app.actions.startup.StartupActionsBean] Server Info: JBoss Web/3.0.0-CR1 

有谁知道怎么才能熬过这个contextPath中,或其他方式?

ps。使用SEAM 2.2.2,Jboss AS6 Final,Richfaces 3.3.3

回答

1

不要使用@Startup,您的组件启动代码被称为上下文是之前完全设置和其他一些工厂目前还无法初始化。

观察org.jboss.seam.postInitialization事件并使用相同的ServletLifecycle.getCurrentServletContext()来获取所需的数据。一个简单的例子:

@Name("contextPath") 
public class ContextPathInit implements Serializable { 
    private String contextPath; 

    @Observer("org.jboss.seam.postInitialization") 
    public void init() { 
     contextPath = ServletLifecycle.getCurrentServletContext().getContextPath(); 
    } 
} 
+0

感谢EmirCalabuch得到它,我测试上面,它仍然只是输出一个空的String ?,事实上,它似乎只在服务器热调用时调用,而不是从冷启动调用? – DaveB

+0

只有在应用程序位于根上下文中时,'getContextPath()'中的空字符串才可以。观察者方法应始终在启动过程结束时调用。如果没有,请检查组件类是否不在'src/hot'文件夹中。另外,请尝试使用'@ Observer'注释中的'create = true'选项。 – EmirCalabuch

+0

啊好的,但我想获得服务器的域名,例如。如果没有明确的话,http://myapp.com。会有更好的方法来做到这一点? – DaveB

0

您是否试图使用getContextName方法从ExternalContext获取它?

FacesContext.getCurrentInstance().getExternalContext().getContextName() 
+0

我相信,这将只能从一个HTTP请求(用户加载网页)调用,我想在应用程序启动 – DaveB

相关问题