1

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 ?!

Roman C
  • 49,761
  • 33
  • 66
  • 176
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173
  • Why did you even define it as a static variable? Should work without static modifier as well... – home Jul 30 '17 at 13:39
  • If I remove static from `myConfig` will be `null` in `getTextProvider` method. making it static was the only way I found to pass this parameter to `getTextProvider`. The `contextInitialized` is called during servelt start and the `SabaStrutsTextProviderFactory` is called during struts start. And every time new instance of `CustomStrutsTextProviderFactory` is created. – Alireza Fattahi Jul 31 '17 at 04:12

1 Answers1

1

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 !!!
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • I tried to `implements DispatcherListener` but 1) I could not find away to get `ServletContext` in `dispatcherInitialized` 2) My `dispatcherInitialized` is never called – Alireza Fattahi Jul 31 '17 at 12:18