【问题标题】:How to write to a HttpServletResponse response object?如何写入 HttpServletResponse 响应对象?
【发布时间】:2012-01-12 05:45:37
【问题描述】:

我有这个动作类,这个类负责我的响应

更新现在传递来自 DownloadStatus 类的响应,但看起来它是空的

public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware
{
    static Logger logger = Logger.getLogger(DownloadStatus.class);
    private HttpServletRequest request;
    private HttpServletResponse response;
    private File cfile;
    private String cfileFileName;

    @Override
    public String execute() 
    {

        logger.debug("Inside DownloadStatus.execute method")

        try {
            ChainsInvoker invoker = new ChainsInvoker()
            def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName)
            if(executionResponse == null || ErrorHandler.checkIfError(executionResponse))
            {
                return ERROR
            }
            response.setContentType("APPLICATION/xml")

            logger.debug("filename: $cfileFileName")

            response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"")
            response.getWriter().print(executionResponse)
            logger.debug("executionResponse :" + executionResponse)
            invoker.invoke(MYChains.clean)
        }catch (Exception exp) {

            logger.error("Exception while Creating Status ")
            logger.error(exp.printStackTrace())

        }
        return NONE
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {     this.request = request; }

    @Override
    public void setServletResponse(HttpServletResponse response) {      this.response = response;   }

    public File getcfile()  {       cfile   }

    public void setcfile(File cfile)    {       this.cfile = cfile  }

    public String getcfileFileName()    {       cfileFileName   }

    public void setcfileFileName(String cfileFileName){     this.cfileFileName = cfileFileName  }
}

及以下类将流写入响应

class DownloadStatusResponse implements Command {   

static Logger logger = Logger.getLogger(DownloadStatusResponse.class);
@Override
public boolean execute(Context ctx) throws Exception 
{
    logger.debug("Inside DownloadStatusResponse.execute() method")
    OutputStream response = null;

    if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0 )
    {
HttpServletResponse resp = ctx.get(ContextParams.response)
/*I am trying to get Response here*/

        response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp)
    }

    logger.debug("Response: " + response)
    ctx.put(ContextParams.response,response);   /*ContextParams is a enum of keywords, having response*/
    return false;
}

private OutputStream downloadStatusFile(String filename,HttpServletResponse resp)
{
    logger.info("Inside downloadStatusFile() method")

    File fname = new File(filename)
    if(!fname.exists())
    {   
        logger.info("$filename does not exists")
        return null
    }
    else
    {

        resp.setContentType("APPLICATION/xml")
/*Exception: cannot setContentType on null object*/

        resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"")

        FileInputStream istr = new FileInputStream(fname)
        OutputStream ostr = resp.getOutputStream()
        /*I need to use resp.getOutputStream() for ostr*/

        int curByte=-1;

        while( (curByte=istr.read()) !=-1)
            ostr.write(curByte)

        ostr.flush();           
    }               
    return ostr
}

}

我的问题是如何将ostr 返回到DownloadStatus 类中的response

更新(工作测试 servlet)

我在下面有这个 servlet,它负责将文件内容放入流中并将其返回给 HttpServletResponse,但我想在上面的代码中使用它

    public class DownloadServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

    String fileName = req.getParameter("zipFile");

    if(fileName == null)      return;

        File fname = new File(fileName);
        System.out.println("filename"); 
        if(!fname.exists())  {System.out.println("Does not exists");            return;}

        FileInputStream istr = null;
        OutputStream ostr = null;
        //resp.setContentType("application/x-download");
        resp.setContentType("APPLICATION/ZIP"); 
        resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"");
        System.out.println(fname.getName()); 
        try {  
          istr = new FileInputStream(fname);
          ostr = resp.getOutputStream();
          int curByte=-1;

                while( (curByte=istr.read()) !=-1)
                    ostr.write(curByte);

          ostr.flush();
        } catch(Exception ex){
          ex.printStackTrace(System.out);
        } finally{
          try {
            if(istr!=null)  istr.close();
            if(ostr!=null)  ostr.close();
          } catch(Exception ex){

              ex.printStackTrace();
            System.out.println(ex.getMessage());
          }
        }  
        try {
            resp.flushBuffer();
        } catch(Exception ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
    }
 }

【问题讨论】:

  • 为什么你可以直接使用流和 Servlet API,而它可以通过流结果来完成
  • ostrOutputStream,但 responseHttpServletResponseostr 返回响应是什么意思?
  • @Umesh:我不熟悉下载东西!所以我来解决@首先我正在关注它,如果有更好的方法,请帮助我:)谢谢
  • @splix:嗨,我更新了我的问题以包括我的测试 servlet,它完成了下载文件的工作

标签: java struts2


【解决方案1】:

据我了解,您所需要的只是如何使用 Struts2 下载文件。

你需要这样的东西是你的 struts.xml 文件

<action name="downloadfile" class="DownloadAction">
           <result name="success" type="stream">
               <param name="contentType">application/pdf</param>
               <param name="inputName">inputStream</param>
               <param name="contentDisposition">attachment;filename="document.pdf"</param>
               <param name="bufferSize">1024</param>
           </result>
       </action>

代码:

public class DownloadAction extends ActionSupport {

  private InputStream inputStream;

  public InputStream getInputStream() {
    return inputStream;
  }

  public void setInputStream(InputStream inputStream) {
    this.inputStream = inputStream;
  }

  public String execute() throws FileNotFoundException {
    String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
    File f = new File(filePath + "/nn.pdf");
    System.out.println(f.exists());
    inputStream = new FileInputStream(f);
    return SUCCESS;
  }
}

【讨论】:

  • 为什么通常不赞成链接到外部资源的主要例子。链接现在已经死了,这个答案没有意义。
  • @thecoshman 我添加了操作代码,希望现在有意义。抱歉,链接断开,我已将其删除。
  • @XCodernice 工作人员。不知道我是怎么回答这个问题的,这并不是我真正想要的,但我还是很感兴趣,并注意到你的链接已经死了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
相关资源
最近更新 更多