这是图片:
我有一个带有表单的html / jsp页面。
<div id = "divAttributes">
<form id = 'fid' method = "post" action = "RunQuery">
Id Number: <input type= "text" name = "foo" id = "txtFoo"/><br/>
<input type = "checkbox" id = "chboxZap" value = "zap"/>Foo<br/>
<input type = "checkbox" id = "chboxBar" value = "bar"/>Bar<br/>
<input type= "submit" id = "btnSubmit" value = "submit" onclick = "setDisabled('divAttributes', true)"/><br/>
</form>
</div>
当用户按下提交按钮时,我想将表单中包含的信息发送到servlet,然后servlet会进行一些处理并返回一个字符串。
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
ReturnCode rc = world.hello.MyMainClass.wait(request.getParameter("foo"));
/*I want to return the RC, which is a bool, a string, and another object, which in this case is a string*/
}
然后应该将该字符串发送到另一个servlet,然后保存一个文件。
我已经有了保存文件的servlet:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition",
"attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
String s = new String(request.getParameter("data"));
InputStream is = new ByteArrayInputStream(s.getBytes());
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
我有两个问题:
第二个servlet在被调用时不会重定向到新页面。它只是立即提供下载对话框。但是,当我调用第一个servlet时,它提供了一个空白的html页面。为什么?
如何将值从servlet返回到调用它的HTML页面,并从那里访问它们?
答案 0 :(得分:1)
JavaScript,更具体地说,Ajax会对您有所帮助。如果您在HTML中包含具有良好Ajax支持的库(例如jQuery),则可以在停留在同一页面时调用您的servlet。
因此,您可以调用使用嵌套Ajax帖子到两个servlet的JavaScript函数,而不是从按钮提交表单:
function submitForm() {
$.post( 'url/to/firstServlet', { text: $('#txtFoo').val() }, function(dataFromFirst) {
$.post( 'url/to/secondServlet', { data: dataFromFirst }, function(dataFromSecond) {
// handle response from second servlet
});
});
}
答案 1 :(得分:0)
使用AJAX!
AJAX允许您创建Ajax Javascript对象,并将HttpResponse返回给该对象。
例如
function myAjaxRequest()
{
var xmlhttp; /*our ajax object*/
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
setVisible('loading', true) ;
/*this function called when ajax state changes*/
xmlhttp.onreadystatechange=function()
{
/*when the query has completed successfully*/
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
/*now you can do what you want with your response text!*/
var mystring= xmlhttp.responseText;
alert(mystring);
}
}
/*the URL query we want to run*/
var query = "RunQuery?foo="+$('#txtFoo').val();
alert(query);
/*AJAX object runs the query*/
xmlhttp.open("GET", query, true);
xmlhttp.send();
}