[英]How to get the ServletContext in Struts 2 factory classes
在 Struts 2 工廠類(例如StrutsTextProviderFactory
)中訪問ServletContext
我使用了以下代碼:
public class CustomStrutsTextProviderFactory extends
StrutsTextProviderFactory implements ServletContextListener{
private static String myConfig;
@Override
protected TextProvider getTextProvider(Class clazz) {
// I can read myConfig here !
}
@Override
public void contextInitialized(ServletContextEvent event) {
myconfig = event.getServletContext().getInitParameter("config");
}
}
它有效,但我認為定義一個static
屬性並以這種方式設置它不是最好的方法。
有沒有更好的辦法 ?!
這不是最好的,也是錯誤的,因為如果您嘗試使用帶有 struts2 配置的工廠,您可能會遇到問題。 servlet上下文是在struts2初始化之前獨立啟動的,所以不能使用需要框架啟動的struts2 api。
如果您需要在 struts2 啟動時初始化您的應用程序,最好的方法是在調度程序初始化事件上。 檢查此答案您應該如何實現調度程序偵聽器。
下面是監聽調度器初始化事件時構造對象的順序:
15:27:50 INFO (org.apache.struts2.spring.StrutsSpringObjectFactory:42) - ... initialized Struts-Spring integration successfully
!!! MyBean !!!
!!! init !!!
jul 18, 2013 3:27:51 PM org.apache.catalina.startup.HostConfig deployDirectory
!!! dispatcherInitialized !!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.