Result的几种通用类型 Dispatcher, Redirect,Chain.以及一些其他模块的几种方法类型,如Velocity.FreeMark.JasperReport 3中模块的返回类型。
public interface Result extends Serializable {
/**
* Represents a generic interface for all action execution results.
* Whether that be displaying a webpage, generating an email, sending a JMS message, etc.
*
* @param invocation the invocation context.
* @throws Exception can be thrown.
*/
public void execute(ActionInvocation invocation) throws Exception;
}
//自定义的Result获得Action返回的类型
package example.result;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
@SuppressWarnings("serial")
public class ResultType implements Result {
public void execute(ActionInvocation invocation) throws Exception{
String resultCode = invocation.getResultCode();
System.out.println("This time of Result code:"+resultCode);
}
}
//Action样例
package example.result;
import java.util.Random;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class TestAction extends ActionSupport{
public String execute() throws Exception{
//产生一个100以内的整数
int random = new Random().nextInt(100);
//根据产生的随机数,分别返回五种不同的字符串
if(random<=20){
return SUCCESS;
}
else if(random<=40){
return ERROR;
}
else if(random<=60){
return LOGIN;
}
else if(random<=80){
return NONE;
}
else{
return INPUT;
}
}
}
Result需要在struts.xml中进行配置
<result-types>
<result-type name="test" class="example.result.ResultType" default="true" />
<!-- 配置test这个返回类型,同时指定test为默认的返回类型 -->
</result-types>
测试程序在控制台中输出 The time of Result code:*** 证明Result被使用。不过Struts2已经定义了许多中返回类型,这些返回类型在日常开发中已经足够使用了。