Tuesday, May 29, 2007

Learning Struts 2 - Zero Configuration

Zero Configuration is a new feature introduced in Struts 2.

If you enable this,
  • No entry is required in struts.xml for defining new actions. Just write your action classes and they will be automatically mapped!!!!
  • Results (views) can be defined using annotations, no need to put entries in struts.xml
Mapping action classes

Modify web.xml and add the package names where your action classes can be located using actionPackages

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>com.mycompany.learning.struts2</param-value>
</init-param>

</filter>




Adding the above init-param will ensure that all actions classes in the package com.mycompany.learning.struts2 will be automatically mapped to the default URLs.

Mapping results views
Result views for an action should be specified using @Result & @Results annotations

For eg; Add the below annotation to your action class if you want to redirect to HelloWorld.jsp


@Result (name="success", value="/HelloWorld.jsp")
public class HelloWorldAction {
...code here...
}


Trouble-Shooting

1. How do I ensure my action class is automatically mapped?

You need to ensure the following:-
  • Check whether you package name is passed as to the FilterDispatcher in web.xml. If your action class is in x.y.z package, giving x.y is not sufficient for the automatic mapping to happen.
  • Your class should extend com.opensymphony.xwork2.ActionSupport or should end with the name Action

2. What will be the URL for my automatically mapped action classes?

If your action class name ends with Action, "Action" will be trimmed from the class name. And the remaining string will be formatted using java bean naming conventions.

Examples: (self-explanatory)
  • HelloAction.java - hello.action
  • HelloWorld.java - helloWorld.action
  • HelloWorldAction.java - helloWorld.action
  • HelloActionWorld.java - helloActionWorld.action