2012-09-23 46 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

相關問題