简体   繁体   中英

How do I return a string from a servlet without leaving the page?

Here's the picuture:

I have a html/jsp page with a form on it.

    <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>

When the user presses the submit button, I want to send the information contained in the form to a servlet, which will then do some processing and return a string.

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*/
}

That string should then be sent to a different servlet, which then saves a file.

I already have the servlet to the file saving:

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();
}

I have two questions:

  1. The second servlet, when called, doesn't redirect to a new page. It just instantly provides the download dialog box. However, when I call the first servlet, it provides a blank html page. Why?

  2. How do I return values from the servlet to the HTML page that called it, and access them from there?

JavaScript and more specifically, Ajax will help you. If you include a library with good Ajax support -- such as jQuery -- in the HTML, you can call your servlet(s) while staying on the same page.

So, instead of submitting the form from the button, you can invoke a JavaScript function that uses nested Ajax posts to the two servlets:

function submitForm() {
  $.post( 'url/to/firstServlet', { text: $('#txtFoo').val() }, function(dataFromFirst) {
    $.post( 'url/to/secondServlet', { data: dataFromFirst }, function(dataFromSecond) {
      // handle response from second servlet
    });
  });
}

Use AJAX!

AJAX allows you to create an Ajax Javascript object, and return the HttpResponse to that object.

eg.

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();     
}       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM