Tuesday, March 3, 2009

Saving Form Parameters In Strtuts 2

This post intends to answer the following questions : -
  1. How to store details entered in a form in a Struts 2 application?
  2. Do we have an action form class in struts 2?
  3. How to use my action class to store form data?
The most important question that needs to be answered here is question number 2. We do not have any action form in struts 2 like it used to be in struts 1.

Struts 2 makes it possible to make use of the action class itself as the class that can store the details submitted by the user in a form or sent as parameters in the request. This task is performed by the ParametersInterceptor. It is the task of the parameters interceptor to inject the values passed in the request to the struts 2 instance fields. This interceptor is used to call the appropriate setter method of the action class to inject the parameter into the instance variable. The only requirement is that you the name of the parameter and the setter must be the same.

For example, suppose that you have a form in which you have a textfield called 'age' which is submitted with the form. Now, to automatically save this value in the action class, you need have a method called setAge(int age), in the action class. The Parameters interceptor takes care of parsing the arguments to the appropriate data type. You can now save the age in a private instance variable. If you create a getter method such as getAge(), then this can also be called directly form the jsp page by using the property tag, if the action class in the value stack. Just make sure that the getter and setter methods are public so that they can be accessibe anywhere.

Happy Programming ;)

Signing Off

No comments: