简体   繁体   中英

Is there any init method given for struts2 action class?

Is there any init method provided for struts 2 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.

Yes there is:

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

Cheers.

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() ).

Yes

init() 

Called after an interceptor is created, but before any requests are processed using intercept , giving the Interceptor a chance to initialize any needed resources.

See this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM