1. 程式人生 > >struts2 中 Preparable 接口實現數據準備

struts2 中 Preparable 接口實現數據準備

con rect rec turn string cat import 實現 his

  

  今天才知道struts還有Preparable接口,實現此接口需要實現其prepare()方法,調用action中其他方法之前會先調用prepare()方法。此接口和方法可以用於初始化一些數據。

測試代碼:

package cn.qlq.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Preparable; @Namespace("/") @ParentPackage("default") public class FirstAction extends ActionSupport implements Preparable { private static final long serialVersionUID = 1L;
private String test; @Override public void prepare() throws Exception { System.out.println("這是所有方法前的處理"); } @Action(value = "test", results = { @Result(name = "success1", location = "/index2.jsp", type = "redirect") , @Result(name
= "error", location = "/index2.jsp") , @Result(name = "success" ,type = "json" , params = {"root","test"}) }) @Override public String execute() throws Exception { test = "test"; return super.execute(); } public String getTest() { return test; } public void setTest(String test) { this.test = test; } }

當我們訪問execute方法的時候會先執行prepare()方法。

  另外,當action種有一個方法叫做haha(),我們可以定義一個prepareHaha()方法,則在訪問haha()之前會先訪問prepareHaha(),再訪問prepare(),最後訪問haha(),如下代碼:

package cn.qlq.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Namespace("/")
@ParentPackage("default")
public class FirstAction extends ActionSupport implements Preparable {

    private static final long serialVersionUID = 1L;
    private String test;
    @Override
    public void prepare() throws Exception {
        System.out.println("這是所有方法前的處理");
    }

    @Action(value = "test", 
            results = { @Result(name = "success1", location = "/index2.jsp", type = "redirect") ,
                        @Result(name = "error", location = "/index2.jsp") ,
                        @Result(name = "success" ,type = "json" , params = {"root","test"}) 
                        })
    @Override
    public String execute() throws Exception {
        test = "test";
        return super.execute();
    }
    
    public void prepareHaha() {
        System.out.println("haha 執行前面");
    }
    @Action(value = "haha" ,results ={@Result(name = "success", location = "/index2.jsp", type = "redirect")} )
    public String haha() throws Exception {
        return super.execute();
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

    
}

結果:

  haha 執行前面
  這是所有方法前的處理

struts2 中 Preparable 接口實現數據準備