0

The problem I am trying to solve is having a javascript function that will perform some functions in sequence.

Step 1) Web client/javascript does some functions locally to the browser.

Step 2) The browser calls a java class/application on the webserver which will perform a number of tasks that only the webserver itself (not the client) can perform.

Step 3) Have the results of step two added to the webpage and displayed in the browser without reloading all the HTML

N.B. Step 2 may take several minutes and it is ok for the client to be essentially inactive during this time.

I'd appreciate any advice or walk throughs/tutorials that may be relevant.

Kind Regards

Balint Bako
  • 2,421
  • 1
  • 12
  • 12
Mark Taylor
  • 1,056
  • 7
  • 14
  • Take a look at this tutorial: http://javapapers.com/ajax/getting-started-with-ajax-using-java/ – Gray Jun 13 '13 at 14:03
  • Step1 is just simply JavaScript, you need an AJAX call in Step2 and you can perform Step3 in the "complete" callback of Step2. – Balint Bako Jun 13 '13 at 14:09

2 Answers2

0

Use jQuery to perform an asynchronous HTTP request(AJAX)

function YOURFUNCTION(){
//Calls servlet
$.post('ServletName',{parameter:value,parameter2:value2,...},function(results) {
  //displays results returned from servlet in specific div(resultsDiv)
  $('#resultsDiv').html(results);
});

}

You need to include the jQuery library on top of your HTML file as:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

You may find more info here

Simple as that.

mario
  • 457
  • 3
  • 16
0

i hope this concise explanation will give you an overview and the understanding you expect.

PART A

SERVER SIDE

In your web server application on your server, if using Java, you are to create a Java servlet class to process data that was submitted from client browser via script or form and to provide dynamic content such as the results of a database query from the client.

Read more on Servlets from:

  1. http://docs.oracle.com/javaee/5/tutorial/doc/bnafe.html
  2. http://en.wikipedia.org/wiki/Java_Servlet
  3. What is Java Servlet?

Also read more about how to register your servlet on the server (web.xml for java Projects)

Example of a servlet:

-================-

@WebServlet(name = "MyServlet", urlPatterns = {"/calculator"}, asyncSupported = true)
public class MyServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Enumeration e = request.getParameterNames(); // parsing the string from client

    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();// eg. "command" from ajax
        String value = request.getParameter(name); // eg. getSum

        if (value.equals("getSum")) {
            // Instantiate a java class and call the method
            // that performs the addition and returns the value
            Calculator calc = new Calculator();

            String answer = (String) calc.getSum();

            if (answer != null) {
                // Set contentType of response to client or browser
                // so that jQuery knows what to expect.
                response.setContentType("text/plain");
                PrintWriter out = response.getWriter();
                // return answer to ajax calling method in browser
                out.print(answer); 
                out.close();
            }
        }
    } // END While LOOP


}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // include method if you call POST in you ajax on client side
}

}

a Java Class for calculations on your server path

public class Calculator {
    public int getSum() {
        return 10+15;
    }
}

-

PART B

CLIENT SIDE – Your Browser

-======================-

You have to visit jQuery website, download and add the jQuery ajax script to your project. “jquery-ui.min.js” is sufficient for this purpose. Add this script to your html or jsp file using the following line:

 <script src="resources/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>

Within your external javascript file or inline javascript include a function to call the servlet and get the sum as follows:

function getSum(){
    $.ajax({
        type: 'GET',       //  type of request to make. method doGet of the Servlet will execute
        dataType: 'text',  // specifying the type of data you're expecting back from the server
        url: 'calculator', // the URL to send the request to. see annotation before class declaration
        data: "command="+"getSum", // Data to be sent to the server (query string)

        // if request fails this method executes
        error: 
        function(e){
            alert('Error. Unable to get response from server');
        },

        // when request is successful, this function executes
        // display the data from server in an alert
        success: 
            function(result){
                if(result) {
                    alert(result);
                }
            }    

   });
}
Community
  • 1
  • 1
ColinWa
  • 663
  • 1
  • 8
  • 21
  • Thanks for this, it's helpful :) I'm very new to Java/Web dev although have some experience in Windows forms apps. Can you describe how you'd implement the example you gave? Specifically you gave three chunks of code: Code Chunk 1 - I don't know where this goes, Code chunk 2 seems to be an independent java class that needs to be compiled separately - if so, what should the location be? Code Chunk three seems to be just javascript and included in the http docs? Can you confirm? Thanks again. – Mark Taylor Jun 14 '13 at 21:30
  • **Code Chunk 1** is a _Servlet_, and is part of the java web app that resides on a web server and its purpose is to respond to requests sent from javascript via Ajax on a browser application (as per Step 2 of your question). Servlet are created as java classes and reside on the **"Source Package"** of your java web application project. A **"URL Pattern"** has to be set whenever you create a servlet. Whenever your POST or GET requests from your client side uses this "url pattern", the listening servlet will execute. See link referenced below. – ColinWa Jun 25 '13 at 08:44
  • I use NetBeans. In order to implement my example, Create a new Project and chose the "Java Web" category, then select "Web Application". Read more on how to create a java web app with a servlet at [Netbeans Ajax Quickstart](https://netbeans.org/kb/docs/web/ajax-quickstart.html) **Code Chunk 2** represents you web application's business logic. It should normally reside in the "Source Package" of your web application. It is instantiated in the servlet and the getSum() method is called. You will have to import this class if it is not in the same package as the servlet class. – ColinWa Jun 25 '13 at 08:44
  • **Code Chunk 3** as you correctly stated is part of your client-side project; the html file that includes your javascript and ajax. Note that in my Ajax example, the "url" parameter uses the "URL Pattern" specified by the servlet. – ColinWa Jun 25 '13 at 08:49