![](/img/trans.png)
[英]How to call action with parameters of JSP Servlet from JavaScript?
[英]JSP - How to call Servlet only after Action finishes executing?
好的,我有一個JSP,一個Servlet和一個Action類。 JSP有一個“下載”按鈕,單擊該按鈕可以調用兩個函數-“ build()”和“ download()”。 “ build()”函數執行一個動作。 該操作將在服務器上創建並生成文件。 “ download()”用於使用servlet從服務器獲取文件,以便用戶下載。
Action.java
-----------
buildFile() {
//build file/writes in the file
}
Servlet.java
-----------
doget(){
//gets the file from the server
}
JSP
---
<script type="text/javascript">
function build() {
//calls buildFile();
//form.submit();
}
function download() {
window.open('/Servlet');
}
</script>
<input type="button" class="button" value="Download" onclick="build();download();"/>
現在的問題是,每當我單擊“下載”時,在build()之后立即將download()稱為。 因此,如果文件中的數據較少,則構建過程將完成,並且用戶可以下載文件。 但是,如果要寫入文件的數據很大,則在“ build()”之后仍會立即將download()稱為IMMEDIATELY,並且用戶只能在其下載的文件中獲得部分數據(因為該文件仍在后台構建)。 我想做一些事情,使download()等待Action(buildFile())完成執行。 同樣,如果沒有form.submit(),則由於某種原因不會調用該動作。 這就是為什么我不能使用“ document.ready”或“ window.onLoad”的原因。 因此,請提出其他建議。 我也嘗試過這個:
function build() {
//calls buildFile();
//form.submit();
download();
}
function download() {
window.open('/Servlet');
}
<input type="button" class="button" value="Download" onclick="build();"/>
但這不起作用。
與其直接調用兩個javascript方法build()和download(),不如使用直接的HTML表單提交到同時生成和下載文件的servlet。
<form action='/Servlet' method='post' target='_blank'>
<input type='hidden' name='param_needed_to_build_file' value='something' />
<input type="submit" class="button" value="Download" />
</form>
target ='_ blank'使它打開一個新窗口。 如果需要,也可以使用method ='get'。 如果需要,您仍然可以使用javascript在另一個窗口中彈出servlet,但是構建和下載都應在servlet中。
在您的Servlet中,實現doGet和/或doPost方法來調用Java函數build()和download(),這兩個函數都將在您的Servlet中。 或者,您可以將build()方法放在servlet中引用和利用的另一個類中。
實際上,通常的做法是構建文件,然后將其直接寫到響應對象中,而不是先寫到文件系統中,然后再讀取它(除非您出於某種原因以后要保存文件)。
我找到了解決方案。 我只調用build(),然后在操作類的build方法的結尾,我就在servlet中調用了doget()方法。
Action.java
-----------
buildFile() {
//build file/writes in the file
Servlet servlet = new Servlet();
servlet.doget();
}
Servlet.java
-----------
doget(){
//gets the file from the server
}
<input type="button" class="button" value="Download" onclick="build();"/>
這將構建我的文件,無論花費多長時間,然后都會向用戶彈出下載框。
您的按鈕說明了一切。 您希望用戶按下“下載”按鈕並獲取文件。 但是必須先構造文件才能提取文件。
這告訴您需要做兩件事; 構建,然后下載。
onclick="buildAndDownload();"
function buildAndDownload(){
// build file
// start the download
}
您甚至可以將這兩個動作的邏輯分為兩個單獨的方法。
下載功能所需要的是一種查詢服務器文件是否准備就緒的方法。
function download (){
while(! fileIsReady()){
Thread.sleep(500);
}
// Start the download
}
當然,如果您知道文件始終在x毫秒后就可以下載了,並且不想構建更多的服務器端功能,則可以調用“ Thread.sleep(1500);”。 等待1.5秒,然后再開始下載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.