简体   繁体   English

如何在 Struts 2 工厂类中获取 ServletContext

[英]How to get the ServletContext in Struts 2 factory classes

To access ServletContext in an Struts 2 factory class ( For example StrutsTextProviderFactory )在 Struts 2 工厂类(例如StrutsTextProviderFactory )中访问ServletContext

I used below code:我使用了以下代码:

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");
        
    }
}

It works but I think define an static property and setting it in this way is not the best approach.它有效,但我认为定义一个static属性并以这种方式设置它不是最好的方法。

Is there a better way ?!有没有更好的办法 ?!

It's not the best and it's wrong, because if you try to use such factory with struts2 configuration, you might have problems.这不是最好的,也是错误的,因为如果您尝试使用带有 struts2 配置的工厂,您可能会遇到问题。 The servlet context is started independently before struts2 is initialized, so you can't use struts2 api that requires the framework being started. servlet上下文是在struts2初始化之前独立启动的,所以不能使用需要框架启动的struts2 api。

The best approach if you need to initialize your application when struts2 has been started is on dispatcher initialize event.如果您需要在 struts2 启动时初始化您的应用程序,最好的方法是在调度程序初始化事件上。 Check this answer how you should implement a dispatcher listener.检查答案您应该如何实现调度程序侦听器。

Below is the order to construct objects when listening on dispatcher initialization event:下面是监听调度器初始化事件时构造对象的顺序:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM