1、自定义返回类,继承StrutsResultSupport类
package cn.jieou.struts.resulttype;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import com.opensymphony.xwork2.ActionInvocation;
import cn.dsna.util.images.ValidateCode;
/**
* 自定义返回类型
* 实现返回图片验证码功能
* @author LMJ
*
*/
public class Captcharesult extends StrutsResultSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
/*
* 定义参数,使用getter\setter方法注入
* */
private Integer width;
private Integer height;
private Integer codeCount;
private Integer lineCount;
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getCodeCount() {
return codeCount;
}
public void setCodeCount(Integer codeCount) {
this.codeCount = codeCount;
}
public Integer getLineCount() {
return lineCount;
}
public void setLineCount(Integer lineCount) {
this.lineCount = lineCount;
}
@Override
protected void doExecute(String finalLocation, ActionInvocation invocation)
throws Exception {
// TODO Auto-generated method stub
HttpServletResponse response = ServletActionContext.getResponse();
//使用验证码jar包
ValidateCode validateCode = new ValidateCode(width, height, codeCount, lineCount);
//以流的形式输出
validateCode.write(response.getOutputStream());
}
}
2、在配置文件注册到strut2中
注意:在当前package里面注册是局部性的,如果比较多地方用到该返回类型,应该使用全局配置
<!-- 这里是我自己定义的一个struts配置,继承struts-default -->
<package name="MJ-struts" extends="struts-default">
<result-types>
<!-- 这里把自定义的返回类型注册到strut2中 -->
<result-type name="captcha" class="cn.jieou.struts.resulttype.Captcharesult"/>
</result-types>
<!-- 这里定义全局返回结果,只要继承了该配置,方法返回结果是captcha的就会执行返回类型对应类中的doExecute方法 -->
<global-results>
<result name="captcha" type="captcha">
<param name="width">200</param>
<param name="height">100</param>
<param name="codeCount">4</param>
<param name="lineCount">4</param>
</result>
</global-results>
</package>