我有一个简单的servlet,可以将视频文件返回给客户端。我想要做的是将文件从URL下载到我的服务器上,然后将新下载的文件发送到客户端。我的问题是,Servlet的入口点位于客户端请求文件的doGet()方法内部。我想一次下载该文件并将其用作静态文件。但是,由于我在doGet()内部调用了download函数,因此客户端尝试获取文件时,它将继续重复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()执行一次。我该怎么做?

最佳答案

您可以在会话变量中添加布尔标志。例如,当第一次执行do get时:

boolean started = true;


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

09-29 22:23