Monday, February 9, 2009

struts.xml in Struts 2

This post intends to answer the following questions :-
  1. Where should I place the struts.xml file in a Struts 2 application.
  2. What should be the contents of a struts.xml file to demonstrate the use of Struts 2.
  3. A minimalist configuration for a seemingly useful Struts 2 application.
As I have already mentioned in my previous post, Struts 2 application is basically just a simple framework that is built to make the life of a web developer easy (At least that's what they say). After you have configured your web deployment descriptor to add Struts 2 capabilities as shown in my previous post here, you need to make a struts.xml file that houses the configuration of Struts 2. This file needs to be placed directly under the 'classes' directory of your web application. In case you are not aware how a web application is structured or where a 'classes' directory is placed, kindly refer here.

Below I am posting a fully configured struts.xml file for a simple Struts 2 application :-

struts.xml
//------Source Code Starts Here------

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">


<struts>
<include file="struts-default.xml"/>
<package name="default" extends="struts-default">
<action name="someAction" class="packageName.ActionClassName">
<result name="success">/somePage.jsp</result>
<result name="error">/someErrorPage.jsp</result>
<result name="input">/someOtherPage.jsp</result>
</action>
</package>
</struts>


//------Source Code Ends Here------

This code snippet demonstrates the use of a struts.xml in a simple Struts 2 application. the only mandatory tags in struts.xml that are required to make your application 'useful' in a minimalist way are :-

<struts>
<include file="struts-default.xml"/>
<package name="default" extends="struts-default">
<action name="someAction" class="packageName.ActionClassName">
<result name="success">/somePage.jsp</result>
</action>
</package>
</struts>

This should be it. Now all that is required of you is to write an action class - 'packageName.ActionClassName' that performs the required action. And off you go. Oh, and dont forget to place the class file that you obtain by compiling the ActionClassName file in the 'classes' directory according to package hierarchy.

Happy Programming ;)

Signing Off
Ryan

No comments: