Developing Struts PlugIn
This article shows you how to develop custom Struts PlugIn and incorporate in your Struts Web Applications. After completing this tutorial you will be able to create your own custom PlugIn for your web application. Struts PlugIn allows the programmer to enhance their web applications. There are many PlugIns available for struts e.g. Struts Tiles PlugIn, Struts Hibernate PlugIn, Struts Spring PlugIn etc. Beside these available PlugIn you can create your own PlugIn.
Understanding PlugIn
Struts PlugIns are configured using the <plug-in>
element within the Struts configuration file. This element has only one valid
attribute, 'className', which is the fully qualified name of the Java class
which implements the org.apache.struts.action.PlugIn interface.
For PlugIns that require configuration themselves, the nested <set-property> element is available.
The plug-in tag in the struts-config.xml file is used to declare the PlugIn to be loaded at the time of server start-up. Following example shows how to declare the Tiles PlugIn:
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property
property="definitions-config"
value="/WEB-INF/tiles-defs.xml"/>
</plug-in>
The above declaration instructs the struts to load and initialize the Tiles plugin for your application on startup.
Writing Struts PlugIn Java Code
In this example we write HelloWorld Struts PlugIn example that will give you idea about creating, configuring and checking Struts PlugIn. Our HelloWorld Stuts PlugIn contains a method called Say Hello, which simply returns HelloWorld message.
Here is code of HelloWorld Struts Plugin:
package roseindia.net.plugin;
|
Configuring PlugIn
To configure the plugin add the following line your struts-config.xml file.
<plug-in className="roseindia.net.plugin.HelloWorldStrutsPlugin">
</plug-in>
Calling PlugIn From JSP Page
Here is the code for calling our PlugIn from jsp page.
<%@page contentType="text/html" import="java.util.*,roseindia.net.plugin.*" %> <% ServletContext servletContext = this.getServletContext(); HelloWorldStrutsPlugin plugin= (HelloWorldStrutsPlugin) servletContext.getAttribute (HelloWorldStrutsPlugin.PLUGIN_NAME_KEY); String strMessage = plugin.sayHello(); %> Message From Plugin: <%=strMessage%> |
Building and Testing
Use ant tool to build the application and then deploy on the server. Enter the url http://localhost:8080/strutstutorial/pages/plugin.jsp in your browser. It display "Hello Plugin" message. Your server console also should display "Hello Plugin" message.
In this section we learnt how to develop simple struts plugin, configure, deploy and test.