[英]How do I return a string from a servlet without leaving the page?
这是图片:
我有一个带有表单的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页面,然后从那里访问它们?
JavaScript,更具体地说, Ajax将为您提供帮助。 如果在HTML中包含一个具有Ajax良好支持的库(例如jQuery ),则可以在停留在同一页面上的同时调用servlet。
因此,无需从按钮提交表单,而是可以调用一个JavaScript函数,该函数使用嵌套的Ajax帖子到两个servlet:
function submitForm() {
$.post( 'url/to/firstServlet', { text: $('#txtFoo').val() }, function(dataFromFirst) {
$.post( 'url/to/secondServlet', { data: dataFromFirst }, function(dataFromSecond) {
// handle response from second servlet
});
});
}
使用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.