class="java" name="code">
  使用Struts2 ,很多人都知道怎么用配置文件的形式实现文件下载 ,但是这样做,要写配置文件确实麻烦,那有没有更方便点的方法呢,有!
使用注解@Annotation的方式就可以省去写配置文件的步骤,在java代码 中的Action上加上“文件下载”的注解即可,具体怎么加呢!?
我们来看一个例子吧,用例子说话胜过千言万语。
 
@Results( { @Result(name = "download", type = "stream", params = { "contentType", "application/vnd.ms-excel",
  "inputName", "inputStream", "contentDisposition", "attachment;filename=/"${downloadFileName}/"", "bufferSize",
  "4096" }) })
public class DownLoad2Action extends ActionSupport{
      public static final String DOWNLOAD
 = "download";
      private String fileName;// 初始的通过param指定的文件名属性
      public String getFile() throws Exception{
             setFileName("add的.xls");
             return “download”;
}
public InputStream getInputStream() throws Exception {
  WritableWorkbook workbook = Workbook.createWorkbook(new File("d://a.xls"));
  WritableSheet sheet = workbook.createSheet("测试", 0);
  Label label = new Label(0, 0, "hello world 从");
  sheet.addCell(label);
  workbook.write();
  workbook.close();
  return new FileInputStream(new File("d://a.xls"));
}
/** 提供转换编码后的供下载
用的文件名 */
public String getDownloadFileName() {
  String downFileName = fileName;
  try {
   downFileName = new String(downFileName.getBytes(), "ISO8859-1");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
  return downFileName;
}
public void setFileName(String fileName) {
  this.fileName = fileName;
}
}
访问的URL
:down-load2!getFile.action
params 中使用键值对进行设置:key1,value1,key2,value2.....;对应response相应头信息