我有一个简单的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()执行一次。我该怎么做?
答案 0 :(得分:1)
您可以向Session变量添加布尔标志。例如,当第一次执行do get时:
boolean started = true;
然后在调用Utility.sendFile()之前检查布尔标志是true还是false并相应地运行该方法。