简体   繁体   中英

How to get the ServletContext in Struts 2 factory classes

To access ServletContext in an Struts 2 factory class ( For example StrutsTextProviderFactory )

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.

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. The servlet context is started independently before struts2 is initialized, so you can't use struts2 api that requires the framework being started.

The best approach if you need to initialize your application when struts2 has been started is on dispatcher initialize event. 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 !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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