2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • See when i say client side, i m essentially referring to the JS code and the generated html code from JSP...i did not quite understand the downvote ... – copenndthagen Sep 29 '11 at 16:58
  • 1
    That downvote was not mine. Perhaps someone got itch from the poor attention for English in your question or was confident that you did poor research effort (I'd imagine that this information can be found just in the DWR guide/tutorial). – BalusC Sep 29 '11 at 17:00
  • The english mistakes is bcoz i m writing this out from my iPad and hence not very fluent typing out...also i have checked the dwr documentation..it does not have this info.. – copenndthagen Sep 29 '11 at 17:18
  • 3
    iPad or not, you could just write "because" and "I" instead of "bcoz" and "i", for example. – BalusC Sep 29 '11 at 17:21
  • Yes, i can..but surely is not very easy to type long words or sentences on it without error :) – copenndthagen Sep 29 '11 at 17:23

5 Answers5

6

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Srikanth Venkatesh
  • 2,812
  • 1
  • 20
  • 13
  • Thx a lot for your reply..u seem to come really close to what i am looking for..Even though, i'll need to go through your example multiple times to understand, at first read, i was just wondering if i can easily scale this to multiple table row cols data..also i am a bit confused if i should consider dojo, as i haven't used it much...my. Simple requirement is making a DWR call and paste the response data into all the 5x5 table or rather div based grid.. – copenndthagen Sep 30 '11 at 16:55
  • Also just to add, the grid needs to be filled in 2 cases ; on page load OR after user clicks on any link... – copenndthagen Sep 30 '11 at 17:18
  • No need to use DOJO check this http://directwebremoting.org/dwr/documentation/browser/util/tables.html – Srikanth Venkatesh Oct 01 '11 at 00:43
  • Thx again..when u say Use JSON object accordingly to populate in table...could u pls let me know how exactly can that be done...from the server side, i understand i need to use Java bean and json at client side..pls confirm.... – copenndthagen Oct 02 '11 at 09:19
  • Also is it possible to use a si ilar logic if i have div-based grid i.e. I need to populate A tableless layout – copenndthagen Oct 02 '11 at 09:20
  • response can be sent as Bean or List from server side .Check the links provided to populate from server side – Srikanth Venkatesh Oct 02 '11 at 17:55
  • Thx a lot again...I just went through the IBM links you gave for DWR and even an article before that (for XML data)... My question is is there something which DWR provides for filling up Div-based grid (i.e. No ..)...something the equivalent of addRows() for table-based grid ? So is there any workaround or direct way in DWR for that ?
    – copenndthagen Oct 03 '11 at 10:52
  • For Div-based grid there is no option I think.There is table based then why Div based ?.Any issues with table with DWR. – Srikanth Venkatesh Oct 03 '11 at 13:13
  • The response contains Json object or List of json objects.You can use this in whatever way as needed ,in a table or a div or any HTML element. – Srikanth Venkatesh Oct 05 '11 at 17:22
  • Ok..the reason i am not using table layout is bcoz my project demands use of only div based layout and that is what most people prefer these days..tableless layouts.. – copenndthagen Oct 06 '11 at 08:08
  • Well i understood the implementation for a table based layout, but not for a div based grid, which is what i have in my case.. – copenndthagen Oct 07 '11 at 16:24
  • All the data is in response as json object or list of json objects then whats the problem in populating in div based grid .. – Srikanth Venkatesh Oct 07 '11 at 16:59
1

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.

FloppyDisk
  • 1,693
  • 16
  • 25
  • Thx a lot for that..I could not find the thing which I am looking for in the examples...While I am quite aware of using JSP, what I am looking for is how to parse the AJAX response dynamically and use it to fill table cells...i.e. say the response returns 5x5 (or rather 25 data points)...I need to be parse them and use them to fill my 5x5 table cells.. – copenndthagen Sep 30 '11 at 06:56
1

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.
claymore1977
  • 1,385
  • 7
  • 12
0
  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
    }
yoprogramo
  • 1,306
  • 9
  • 14
  • Do you mean code? There are lot of ways to acomplish what you nedd. The basis are than the ajax function should return a List and them from js you can access each element of the list as data[index]. If your element inside the list is another list you can access again using the same way data[index1][index2]. Just remember the final object in the list are defined as bean in the dwr.xml. – yoprogramo Oct 09 '11 at 15:05
  • Could u provide any example for the 2 things u just mentioned; returning as List and the corresponding parsing in Javascript..I'll be able to accept only if u could provide a detailed sample.. – copenndthagen Oct 09 '11 at 16:36
0

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.

yoprogramo
  • 1,306
  • 9
  • 14
  • Thx a lot for that...2 things; one is that i do not want to output the complete html string..it should be something like there will be placeholders already present and i'll just fill them by parsing the response and second i plan to use div-based grid for my table i.e. Same grid will be created but without using table tag..thx – copenndthagen Oct 09 '11 at 17:50
  • Also can we extend this logic to a multi-dimensional array like say a 2-dimensional array? – copenndthagen Oct 09 '11 at 18:00
  • No problem with using placeholders, just use javascript functions to modify its contents. I have not tested using a list property, but you can convert any java object to js usin dwr, so, I think it is possible to send a list of lists. – yoprogramo Oct 10 '11 at 06:30