Stream result type是Struts2中比较有用的一个feature。特别是在动态生成图片和文档下载的情况下

1:图片验证码:

Action类,action主要要提供一个获取InputStrem的方法:

public class CheckCodeAction extends ActionSupport implements SessionAware {
private Logger log = LoggerFactory.getLogger(this.getClass());
private InputStream imageStream;
private Map session;

public String getCheckCodeImage(String str, int show, ByteArrayOutputStream output) {
Random random = new Random();
BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_3BYTE_BGR);
Font font = new Font("Arial", Font.PLAIN, 24);
int distance = 18;
Graphics d = image.getGraphics();
d.setColor(Color.WHITE);
d.fillRect(0, 0, image.getWidth(), image.getHeight());
d.setColor(new Color(random.nextInt(100) + 100, random.nextInt(100) + 100, random.nextInt(100) + 100));
for (int i = 0; i < 10; i++) {
d.drawLine(random.nextInt(image.getWidth()), random.nextInt(image.getHeight()), random.nextInt(image.getWidth()),
random.nextInt(image.getHeight()));
}
d.setColor(Color.BLACK);
d.setFont(font);
String checkCode = "";
char tmp;
int x = -distance;
for (int i = 0; i < show; i++) {
tmp = str.charAt(random.nextInt(str.length() - 1));
checkCode = checkCode + tmp;
x = x + distance;
d.setColor(new Color(random.nextInt(100) + 50, random.nextInt(100) + 50, random.nextInt(100) + 50));
d.drawString(tmp + "", x, random.nextInt(image.getHeight() - (font.getSize())) + (font.getSize()));
}
d.dispose();
try {
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
log.warn("生成验证码错误.", e);
}
return checkCode;
}

public String execute() throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
String checkCode = getCheckCodeImage("ABCDEFGHJKLMNPQRSTUVWXYZ123456789", 4, output);
this.session.put(Constants.CHECK_CODE_KEY, checkCode);
//这里将output stream转化为 inputstream
this.imageStream = new ByteArrayInputStream(output.toByteArray());
output.close();
return SUCCESS;
}

public InputStream getImageStream() {
return imageStream;
}

public void setSession(Map session) {
this.session = session;
}

struts配置文件:

<action name="checkCode" class="CheckCodeAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<!-- 指定提供InputStream的filed name -->
<param name="inputName">imageStream</param>
<param name="bufferSize">1024</param>
</result>
<interceptor-ref name="defaultStack"/>
</action>

2:文件下载:

我这里的应用是POI在内存中生成excel文件供客户端下载。struts.xml中的配置如下:

<action name="jxcQuery_*" class="com.chengzhong.action.JxcChaXunAction" method="{1}">
<result name="success">jxcchaxun.jsp</result>
<!--进销存信息导出为excel -->
<result name="toexcelOK" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="inputName">excelIS</param>
</result>
<result name="error">../404.htm</result>
</action>

1.type="stream"           把一般内容输出到流

2.参数contentType的地方指定为application/vnd.ms-excel
3.设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名。这里使用的是动态文件名,${fileName}。它将通过 Action 的 getFileName() 获得文件名。也就是说Action里面要有一个getFileName ()的方法。

public String getFileName() {
String fileName = "进销存信息统计表.xls"
try {
//中文文件名需要转码为 ISO8859-1,否则乱码
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "jxc.xls";
}
}

或者Action 里面有一个fileName的属性,提供它的set 和get 方法。在程序合适的位置给fileName赋值。这两者本质上应该是一样的。
我刚开始没有用注释处的方法转码,用中文做文件名的时候,它就象前面说的用浏览的页面名作为文件名了。

4.<param name="inputName">excelIS</param>
     参数inputName指定输入流的名称。和前面的文件名一样,Action里或者提供一个getExcelIS()的方法,或者提供excelIS属性。

5.对流的操作:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
   
   /************************************************************/ 
    DataImportAndExportTool.InfoToExcel(Info, sheetName).write(baos);
    byte[] ba = baos.toByteArray(); 
    baos.close(); 
    excelIS = new ByteArrayInputStream(ba);       
   /*******************************************************************/
   //DataImportAndExportTool.InfoToExcel(Info, sheetName).write(fOut);     //这样excel表保存在了服务器上
   
  } catch (Exception e) {
   
   e.printStackTrace();
  }
    
   return "toexcelOK";、

DataImportAndExportTool.InfoToExcel(Info, sheetName)是我生成excel的方法,info是一个list,sheetName 是工作薄名,这句执行后生成了一个workbook。

ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的实例向数组中写入或读出byte型数据。在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。

ByteArrayOutputStream用途很多。其中缓冲是一个。对象的深浅复制也会用到

注意:以下是一些参数说明

contentType

内容类型,和互联网MIME标准中的规定类型一致,例如text/plain代表纯文本,text/xml表示XML,image/gif代表GIF图片,image/jpeg代表JPG图片

inputName

下载文件的来源流,对应着action类中某个类型为Inputstream的属性名,例如取值为inputStream的属性需要编写getInputStream()方法

contentDisposition

文件下载的处理方式,包括内联(inline)和附件(attachment)两种方式,而附件方式会弹出文件保存对话框,否则浏览器会尝试直接显示文件。取值为:

attachment;filename="struts2.txt",表示文件下载的时候保存的名字应为struts2.txt。如果直接写filename="struts2.txt",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于这样的写法:inline; filename="struts2.txt"

bufferSize

下载缓冲区的大小

。在这里面,contentType属性和contentDisposition分别对应着HTTP响应中的头Content-TypeContent-disposition头。

struts2 中 result type="stream"的更多相关文章

  1. Struts2 中result type属性说明

    Struts2 中result type属性说明 首先看一下在struts-default.xml中对于result-type的定义: <result-types><result-t ...

  2. struts2文件下载 <result type="stream">

    <!--struts.xml配置--> <action name="download" class="com.unmi.action.DownloadA ...

  3. Struts2 中 result type=”json” 的参数解释

    转自:http://wangquanhpu.iteye.com/blog/1461750 1, ignoreHierarchy 参数:表示是否忽略等级,也就是继承关系,比如:TestAction 继承 ...

  4. struts2 action result type类型

    struts2 action result type类型 1.chain:用来处理Action链,被跳转的action中仍能获取上个页面的值,如request信息. com.opensymphony. ...

  5. struts2.xml 中result type属性说明

    chain           用来处理Action链,被跳转的action中仍能获取上个页面的值,如request信息.           com.opensymphony.xwork2.Acti ...

  6. Struts2中 Result类型配置详解

    一个result代表了一个可能的输出.当Action类的方法执行完成时,它返回一个字符串类型的结果码,框架根据这个结果码选择对应的result,向用户输出.在com.opensymphony.xwor ...

  7. Struts2 语法--result type

    result type: dispatcher,redirect:只能跳转到jsp,html之类的页面,dispatcher属于服务器跳转, redirect属于客户端跳转 chain: 等同于for ...

  8. 04. struts2中Result配置的各种视图转发类型

    概述 <action name="helloworld" class="com.liuyong666.action.HelloWorldAction"&g ...

  9. Struts2.xml中result type属性说明

    在struts2配置XML里,result中type属性有以下几种: 1.dispatcher:服务器跳转到前台,后面跟着可以是JSP.htm等等前台页面,默认是这种. 2.redirect:客户端跳 ...

随机推荐

  1. 数据结构( Pyhon 语言描述 ) — — 第4章:数据和链表结构

    数据结构是表示一个集合中包含的数据的一个对象 数组数据结构 数组是一个数据结构 支持按照位置对某一项的随机访问,且这种访问的时间是常数 在创建数组时,给定了用于存储数据的位置的一个数目,并且数组的长度 ...

  2. SSM整合shiro

    采用maven构建项目 1pom.xml中加入shiro依赖 <!-- shiro --> <dependency> <groupId>org.apache.shi ...

  3. HDU 1257 最少拦截系统(最长上升子序列)

    题意: 给定n个数, 然后要求看看有多少对不上升子序列. 分析: 求出最长上升子序列, 那么整个序列中LIS外的数都会在前面找到一个比自己大的数, 所以不上升子序列最多有最长上升子序列个数个. 关于求 ...

  4. 跟初学者学习IbatisNet第二篇

    在上一篇里面我们知道了什么是IbatisNet,并且知道了如何用IbatisNet进行简单的增删改查的操作,在这一篇文章里面我们主要介绍一下IbatisNet操作存储过程. 我们一般把存储过程分为两种 ...

  5. Ext.js双击事件

    /** * 联系人列表panel */ Ext.define('Op.OpBill.OpBillCustLinkGridPanel', { extend: 'Ext.grid.Panel', id: ...

  6. Codeforces Round #386 (Div. 2) A+B+C+D!

    A. Compote 水题(数据范围小都是水题),按照比例找最小的就行了,3min水过. int main() { int a,b,c; while(~scanf("%d%d%d" ...

  7. 聊聊flink的log.file配置

    本文主要研究一下flink的log.file配置 log4j.properties flink-release-1.6.2/flink-dist/src/main/flink-bin/conf/log ...

  8. 洛谷 P 1018 乘积最大 ==Codevs

    题目描述 今年是国际数学联盟确定的“2000――世界数学年”,又恰逢我国著名数学家华罗庚先生诞辰90周年.在华罗庚先生的家乡江苏金坛,组织了一场别开生面的数学智力竞赛的活动,你的一个好朋友XZ也有幸得 ...

  9. linux C 中的volatile使用

    一个定义为volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了.精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存 ...

  10. Oracle Spatial中的空间索引

    转自cryolite原文 Oracle Spatial中的空间索引 Oracle Spatial可对空间数据进行R-tree索引,每个空间图层(Spatial Layer)的空间索引元信息都可以在US ...