接上次的Struts自定义标签,这次说一下Struts的自定义返回类型,我们在实际的应用中,Struts原生的返回类型是不够用的,比如json或者file类型,需要自己写io流处理,过程大致相同且相对繁琐,如果可以自己封装一下,使用起来事半功倍。
实现过程也不复杂,首先配置strtus.xml
<package name="feng" extends="struts-default"> <result-types> <result-type name="ajax" class="com.struts.extend.result.AJAXResult"> </result-type> <result-type name="excel" class="com.struts.extend.result.ExcelResult"> </result-type> <result-type name="file" class="com.struts.extend.result.FileResult"> </result-type> </result-types> <action name="testAction" class="testAction"> <result name="success">/feng/test.jsp</result> <result name="export" type="excel"></result> </action> </package>
不同的type类型对应不同的class(需要继承com.opensymphony.xwork2.Result),类定义代码如下:
package com.struts.extend.result;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
/**
* @author songfeng
* @version 1.0
* @since 2015-9-18
*/
public class AJAXResult implements Result
{
private String ajax;
private HttpServletResponse rep;
private String chartSet = "UTF-8";
private static final long serialVersionUID = 3841999252996023829L;
public void execute(ActionInvocation invocation) throws Exception
{
this.ajax = ((String) invocation.getStack().findValue("ajax"));
if (this.ajax == null)
{
throw new NullPointerException("没有定义ajax字符串结果集合,或者没有提供get方法");
}
this.rep = ServletActionContext.getResponse();
this.rep.reset();
this.rep.setContentType("text/html; charset=" + this.chartSet);
ServletOutputStream os = this.rep.getOutputStream();
os.write(this.ajax.getBytes(this.chartSet));
os.flush();
os.close();
}
public String getChartSet()
{
return this.chartSet;
}
public void setChartSet(String chartSet)
{
this.chartSet = chartSet;
}
}
对应的Action代码中增加ajax字段的get,set方法,其他就是具体的流操作,file类型和excel类型的代码不赘述,需要的参数通过Action带过来,具体的文件生成逻辑自己添加进来即可。