使用的是spring3 mvc,正在做的一个功能中,需要把一个字节数组动态生成为word供下载,并且,因为使用了ajax(extjs)需要返回一个json对象给前台,做一些处理,但是遇到了严重问题,因为输出word,需要的是输出流response.getoutputstream,而json对象需要response.getwriter输出,结果总是报错,google之后,知道是因为这两个方法冲突,请高手们指点迷津,又没有什么办法来处理我的这个需求,部分代码如下
@RequestMapping(params = "method=runTemplate")
public void runTemplate(HttpServletResponse response,HttpServletRequest request)throws Exception
{
  ……
  byte[] b=ParseWordTemplate.parseTemplate(in,map);  
  response.setContentType("application/msword");
  response.setHeader("Content-disposition","attachment;filename=Example.doc");
  response.setContentLength(b.length);
  ServletOutputStream sos = response.getOutputStream();
  sos.write(b, 0, b.length);
  sos.flush();
  sos.close();
   
  PrintWriter out = response.getWriter();
  out.print("{success:true,msg:'保存成功'}");
  out.flush();
  out.close();
  ……
}

解决方案 »

  1.   

    无法解决。
    一个请求不可能有两个响应体。
    拆成两个Action,用一个页面包含一个链接的方式给出word下载。前面那个页面中可以返回json给浏览器。
      

  2.   

    何谓下载?如果你打算给客户“另存链接为”那样单独保存这个文件到磁盘上的话,那这个响应页面就只需要就给出一个 URL,当用户点击了那个 URL 之后才真正的生成  word 并写出内容,也就是说关键在于,两件事你在一步想做完它,所以出错了。