【问题标题】:Is there any init method given for struts2 action class?struts2 动作类是否有任何 init 方法?
【发布时间】:2009-05-29 12:52:46
【问题描述】:

是否有任何为 struts 2 动作类提供的 init 方法可以在该动作类的每个方法之前调用?

例如,我有一个用于 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";
       }
}

现在在上面的代码中,当调用getAllEmployees()deleteEmplyee() 的struts 操作时,我希望首先执行init() 方法。我们可以通过从两个函数中调用它来运行它。

但是 struts 2 中是否有任何规定会在每次调用时自动运行 init 方法,或者 struts 2 是否为动作类提供了任何此类方法?

如果有人知道,请告诉我。

谢谢。

【问题讨论】:

    标签: java struts2


    【解决方案1】:
    【解决方案2】:

    是的,有:

    首先,您的操作类必须实现Preparable interface。然后,您的操作必须实现 Preparable.prepare() 方法。 Struts 2 将在每次调用您的操作方法之前执行 prepare()。

    干杯。

    【讨论】:

      【解决方案3】:

      准备拦截器是很重要的。如果您的操作使用默认拦截器堆栈,只需将您的 init() 方法重命名为 prepare()

      如果您的操作类有多个操作方法(如 createEmployee() 或 deleteEmployee()),您可以使用名为 prepare&lt;*ActionMethodName*&gt;() 的方法为具体方法做具体准备(例如 prepareDeleteEmployee())。

      【讨论】:

        【解决方案4】:

        是的

        init() 
        

        在创建拦截器之后调用,但在使用拦截处理任何请求之前,让拦截器有机会初始化任何所需的资源。

        See this

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-01
          • 1970-01-01
          • 2014-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多