tags:

views:

1468

answers:

3

Hello Frieds,

Is there any init method provided for struts action class that can be called before every method of that action class?

For example, I have an action class for struts 2 as given below

import com.opensymphony.xwork2.ActionSupport;

public class EmployeeAction extends ActionSupport{

private  DepartmentDaoService deptService = new DepartmentDaoService() ;
private  EmployeeDaoService empService = new EmployeeDaoService();
private Employee employee;
private List<Employee> employees;
private List<Department> departments;

   public void init()
   {
      //Do initialization stuff here
   }
   public String getAllEmployees(){
      employees = empService.getAllEmployees();
      return "success";
   }


   public String deleteEmployee(){
    empService.deleteEmployee(employee.getEmployeeId());
    return "success";
   }

}

Now in above code when struts action for getAllEmployees() and deleteEmplyee() is called I want init() method to execute first. We can run it by calling it from both functions.

But is there any provision given in struts 2 that will run init method automatically on each call or struts 2 provides any such method for action clases?

Please tell me if anyone knows.

Thanks.

+4  A: 

Take a look at the Preparable interface and the Prepare Interceptor

Guido
A: 

Prepare Interceptor is way to go. If your action is using default interceptor stack just rename your init() method to prepare().

If your action class has multiple action methods (like createEmployee() or deleteEmployee()) you can do specific preparation for concrete method with method named prepare<*ActionMethodName*>() (eg prepareDeleteEmployee()).

rdk
Thanks rdk.It is very helpfull information.
amar4kintu
+1  A: 

Yes there is:

First of all, your action class must implement the Preparable interface. Then, your action must implement Preparable.prepare() method. Strut 2 will execute prepare() everytime before it invokes your action method.

Cheers.