简体   繁体   English

是否为struts2动作类提供了任何init方法?

[英]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? 是否为struts 2动作类提供了可以在该动作类的每个方法之前调用的init方法?

For example, I have an action class for struts 2 as given below 例如,我有一个struts 2的动作类,如下所示

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. 现在在上面的代码中,当调用getAllEmployees()deleteEmplyee() struts动作时,我希望首先执行init()方法。 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? 但是struts 2中是否有任何规定会在每次调用时自动运行init方法,或者struts 2为action clases提供任何此类方法?

Please tell me if anyone knows. 如果有人知道,请告诉我。

Thanks. 谢谢。

Yes there is: 就在这里:

First of all, your action class must implement the Preparable interface . 首先,您的操作类必须实现Preparable接口 Then, your action must implement Preparable.prepare() method. 然后,您的操作必须实现Preparable.prepare()方法。 Struts 2 will execute prepare() everytime before it invokes your action method. Struts 2每次调用你的action方法之前都会执行prepare()。

Cheers. 干杯。

Prepare Interceptor is way to go. Prepare Interceptor是要走的路。 If your action is using default interceptor stack just rename your init() method to prepare() . 如果您的操作使用默认拦截器堆栈,则只需将init()方法重命名为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() ). 如果您的操作类具有多个操作方法(如createEmployee()或deleteEmployee()),则可以使用名为prepare<*ActionMethodName*>() (例如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. 在创建拦截器之后调用,但在使用拦截处理任何请求之前调用,使Interceptor有机会初始化任何所需的资源。

See this 看到这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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