Programitically loading a struts.xml file
Why I needed to do this is covered in my next post as it builds on the information here. If you need to use plugins in your web application that are struts2 enabled then you should first read this and then the next post.The code that does the programitic loading
The import statements:
import org.apache.struts2.dispatcher.Dispatcher;
import com.opensymphony.xwork2.config.ConfigurationManager;
import org.apache.struts2.config.StrutsXmlConfigurationProvider;
The code that does the work:
String strutsXMLLocation = "/plugins/myplugin/struts.xml"
/* Get the Dispatcher from the ServletContext where the modified org.apache.struts2.dispatcher.FilterDispatcher
* stored it.
*/
Dispatcher dispatcher = (Dispatcher) servletContext.getAttribute("STRUTS_DISPATCHER");
ConfigurationManager configurationManager = dispatcher.getConfigurationManager();
// Create a new configurationManager for this PLUGIN_STRUTS_XML_FILE
StrutsXmlConfigurationProvider strutsXmlConfigurationProvider = new StrutsXmlConfigurationProvider(strutsXMLLocation, false, servletContext);
// Add the strutsXmlConfigurationProvider to the configuratioManager configurationManager.addConfigurationProvider(strutsXmlConfigurationProvider);
// This is the important bit, reload the configurationManager so that it will acknowledge that the new PLUGIN_STRUTS_XML_FILE file has been registered
configurationManager.reload();
You will see that I get the dispatcher from the ServletContext but it needs to get there first. That is where the modification to to the FilterDispatcher comes in. To modify the FilterDispatcher I created a folder structure in my own source code that matched that of the FilterDispatcher, so org.apache.struts2.dispatcher and then I copied the source code of the FilterDispatcher in there. The only modification to the FilterDispatcher is in the init() method where I added:
filterConfig.getServletContext().setAttribute("STRUTS_DISPATCHER", dispatcher);That adds the Dispatcher to the servletContext so my code can now access it. Without doing this there does not appear to be a way to get the Dispatcher that is used to initialise Struts. You can only create a new one which is no good as it doesn't contain the default configuration files such as struts-default.xml and without that, the struts.xml file you are trying to load programitically will fail. The rest of my code should look fairly self explanatory from there on.
That's it. If you need to know how to modify the classloaders that Struts uses then you should look at my next post as well. I needed to modify them in order to have plugins in my web application that were Struts2 aware.
14.02.2009 06:47 - Posted by doahh - Comments: 0 - Java

Comments: