0

我有一个简单的 servlet,可以将视频文件返回给客户端。我想要做的是将文件从 URL 下载到我的服务器上,然后将新下载的文件发送到客户端。我的问题是 servlet 的入口点在客户端请求文件的 doGet() 方法内。我想下载一次文件并将其用作静态文件。但是,因为我在 doGet() 中调用了下载函数,当客户端尝试获取文件时,它会不断重复 doGet() 中发生的所有事情,并且我的文件不断被覆盖。它确实减慢了整个过程。无论如何我可以只调用一次下载功能吗?

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
  answerRequest(request, response); 
}
...

public void answerRequest(HttpServletRequest request, HttpServletResponse response)              
               throws IOException{
  String requestedFile = request.getPathInfo();

  URL newURL = "fixed URL content";
  HttpURLConnection connection = (HttpURLConnection) newURL.openConnection();


  sendFile(connection,  request, response); 
}

...

public void sendFile(HttpURLConnection connection, HttpServletRequest request, HttpServletResponse response){
  InputStream input = null;
  FileOutputStream output = null;


 File videoFile = new File("path-to-file");
 input = connection.getInputStream();
 output = new FileOutputStream(videoFile);
 Utility.download(input, output,  0, connection.getContentLength()); //this is where the file is downloaded onto my server)


 connection.disconnect();
 close(output);
 close(input);

 //this is where the file is sent back to client
 Utility.sendFile(videoFile, response, request,true);
...
}   

如您所见,所有这些功能都会在每次 doGet() 发生时发生。但我只希望 Utility.download() 执行一次。我该怎么做?

4

1 回答 1

1

您可以将布尔标志添加到 Session 变量。例如,第一次执行 do get 时:

boolean started = true;

然后在您调用 Utility.sendFile() 之前检查布尔标志是真还是假并相应地运行该方法。

于 2013-08-07T00:31:42.950 回答