Thursday, September 27, 2007

Struts2 - Part II : Moving ahead

Configuration :
A typical web.xml file of Struts 1


    <servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>



<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>
In Struts 2 the most significant change is that the dispatcher has been changed from a servlet to a servlet filter.


    <filter>

<filter-name>webwork</filter-name>

<filter-class>

org.apache.struts.action2.dispatcher.FilterDispatcher

</filter-class>

</filter>



<filter-mapping>

<filter-name>webwork</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>
For Struts, the servlet configuration provides an init-param tag that defines the names of the files used to configure Struts. Struts2 does not have such a configuration parameter. Instead, the default configuration file for Struts2 has the name "struts.xml" and needs to be on the classpath of the web application.

A Struts 2 : Struts.xml file

<struts>

<include file="struts-default.xml"/>



<constant name="struts.enable.DynamicMethodInvocation" value="false" />

<constant name="struts.devMode" value="true" />



<!-- Add packages here -->

<package name="default" extends="struts-default">



<action name="home" class="com.dev.mystruts2.MyAction">

<result>/WEB-INF/pages/helloWord.jsp</result>

</action>

</package>

</struts>


Struts 1 Action Class :


public class MyAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// do the work
return (mapping.findForward("success"));
}
}


Struts 2 Action :


public class MyAction {
public String execute() throws Exception {
// do the work
return "success";
}
}


The first thing you may have noticed is that the action doesn't extend any classes or interfaces. In fact, it goes further than this. By convention, the method invoked in the processing of an action is the "execute" method - but it doesn't have to be. Any method that follows the method signature public String methodName() can be invoked through configuration.

Next, the return object is a String. If you don't like the idea of string literals in your code, there is a helper interface Action available that provides the common results of "success", "none", "error", "input" and "login" as constants.




No comments:

Post a Comment