copenndthagen
copenndthagen

Reputation: 50722

Use an Ajax response in JSP

I have a JSP page which has nothing but a normal HTML table with five rows and five columns.

Now I am making an Ajax call and get a response back. Now once I have the response back, I need the data to be filled in appropriate cells of the table.

So my question is;

  1. Should I use JSON for building the response?
  2. How do I handle the data back at the JSP level. That is, once I have the response from the server?

Just as additional information, I am using DWR which is nothing but calling a Java method (which builds the response) from inside JavaScript code.

Upvotes: 2

Views: 10737

Answers (5)

Srikanth Venkatesh
Srikanth Venkatesh

Reputation: 2812

Let's consider this Java class.

    class Employee
    {
        int id;
        String eName;
        // Setters and getters
    }

In JavaScript, the JSON object:

 var employee = {
     id   : null,
     name : null
 };

This is the call to a Java method from a JavaScript function:

   EmployeeUtil.getRow(employee,dwrData);

In getRow() of the EmployeeUtil class, the return type of method will be Employee:

   Employee getRow();

So using the setters of Employee set the data. dwrData is the callback function.

function dwrData(data) {
    employee=data;
}

The data returned, which is an Employee bean, will be in the callback function.

Just initialize this in the JavaScript JSON object.

Use a JSON object accordingly to populate the table.

EDIT :

You can use List getRow() instead of Employee getRow(), returning a list of rows as a List instead of a Bean.

Now the response contains list as data.

Refer to Populate rows using DWR.

Check these examples to populate data in table:

Should I use JSON for building the response?

  • No need to pass JSON in response. Instead return a Bean of a class as mentioned above.

  • A list can be passed as a response, also as mentioned above.

How do I handle the data back at the JSP level. That is, once I have the response from the server.

Check the explanation above and the examples of the given links to handle the response in JSP and display the response data in a table.

Upvotes: 6

yoprogramo
yoprogramo

Reputation: 1306

Ajax part: We return a list of objects:

public List<IdTexto> getPaisesStartingBy(String texto,String locale){
        List<IdTexto> res = new ArrayList<IdTexto>();
// Fill the array
return res;
}

The IdTexto is a simple bean with geters and setters:

public class IdTexto {

    private int id;
    private String texto;
    private String texto2;
// getters and setters
}

And it is defined in the dwr.xml as bean:

<convert converter="bean" match="com.me.company.beans.IdTexto"/>

And the class containing the java function is defined as creator:

<create creator="new" javascript="shopdb">
    <param name="class" value="com.me.company.ajax.ShopAjax"/>
</create>

In the jsp, we define a function javascript to retrieve the List of starting by some text object in this way:

shopdb.getPaisesStartingBy(req.term,'<s:text name="locale.language"/>', writePaises);

And the corresponding function to write down the texts:

function writePaides (data) {
var result="<table>";
for (i=0; i<data.length;i++) {
 id = data[i].id;
 texto=data[i].texto;
 texto2=data[i].txto2;
 // now we write inside some object in the dom
 result+="<tr><td>"+id+"</td><td>"+texto+"</td><td>"+texto2+"</td></tr>";
}
result+="</table>";
 $("tabla").innerHTML=result;
}

If you, instead of a bean have some other object you'll access the properties in the same way.

Upvotes: 0

yoprogramo
yoprogramo

Reputation: 1306

  1. If you use DWR you don't need to use JSON, it uses internally.
  2. Use javascript , the jsp code is out-of-scope. The page has been generated so you only can modify the DOM using javascrip

There are lot of examples doing what you need in DWR tutorials. I suppose you need just do something as:

    dwrobject.funtionAjax(param,returnFunction);
...
    function returnFunction(data) {
// use javascript to change the dom
    }

Upvotes: 0

Pintobean77
Pintobean77

Reputation: 1415

What I do quite frequently is setup two servlets for this situation:

MyServlet
MyAJAXServlet

MyServlet handles the normal HTTP requests and (usually) ends up using a RequestDispatcher to forward the request to a JSP.

Example:

public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = -5630346476575695999L;
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGetAndPost(req, res);
    }
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGetAndPost(req, res);
    }
    private final void doGetAndPost(HttpServletRequest req,
            HttpServletResponse res) throws ServletException, IOException {
        /*
         * Handle the response here, manipulate the 'MODEL'
         */
        /*
         * Forward to the 'VIEW' (No Baba Wawa jokes please)
         */
        RequestDispatcher rdis = req.getRequestDispatcher("Path/To/My/JSP");
        rdis.forward(req, res);
    }
}

Where as the AJAX servlet checks the request's parameter list for presence of a 'command':

public class MyAJAXServlet extends HttpServlet {
    private static final long serialVersionUID = -5630346476575695915L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGetAndPost(req, res);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGetAndPost(req, res);
    }

    private final void doGetAndPost(HttpServletRequest req,
            HttpServletResponse res) throws ServletException, IOException {

            String cmd = req.getParameter("cmd");
            if (cmd == null || cmd.length() < 1) {
                /* Custom fail mode here, perhaps toss back failure HTML */
                return;
            }

            /* Easily implement command pattern here, but for simplicity, we will use an if tree */

            if (cmd.equalsIgnoreCase("getSomeData")) {
                String out = "<tr><td>ExampleCell in ExampleRow</td></tr>";
                res.getWriter().append(out);
                return;
            } else if (cmd.equalsIgnoreCase("someOtherCommand")) {
                /* Do something else */
            }

    }
}

If you format your JSP to allow for bulk replacement of html elements like so:

<table id="pleaseReplaceMyContentsTABLE">
    <tr><td>&nbsp;</td></tr>
</table>

Then it becomes very easy to dynamically modify a web pages content (I use JQuery for this example):

var url = "http://mydomain.whatever/myapp/MyAJAXServletMappedURL?cmd=getSomeData";
$.post(url, function(data) {
    //Message data a bit & display
    $("#pleaseReplaceMyContentsTABLE").html(data);
});

Some limitations with sending back preformatted HTML from the AJAX Servlet:

  1. If you are sending back a moderate to large amount of data, then your webserver will easily become overloaded when the number of clients starts to rise. Aka, it won't scale well.
  2. Java code that is formatting HTML to send to a client can get ugly and hard to read. Quickly.

Upvotes: 1

FloppyDisk
FloppyDisk

Reputation: 1703

JSP pages are dynamically generated servlets. Once a user hits a JSP page, they receive dynamically generated HTML that no longer talks to the JSP page that generated it unless they complete an action such as hitting "refresh" or submitting a form. Check out the JSP Page at Oracle for more info and Wikipedia for a decent high level explanation of JSP technology.

To handle the AJAX, you're going to need to define a new network endpoint capable of processing the XML requests coming up from the Javascript. See this example, this library, or this JSON Example.

Upvotes: 1

Related Questions