PDA

View Full Version : Communication between JSP and JS



g99
27 Jul 2009, 3:48 AM
Hi Everyone!

I'm quite new to Web development so please bear with me.



First, I'll give a short description about the project I am currently working on:
I have a database table which stores information about other tables like database id, schema name, table name, etc... I made an API to retrieve information from this table (it uses JDBC). It gives an ArrayList to the user which stores ResultWrapper object. ResultWrapper is a value object to wrap the record of the table I mentioned above.

I made the UI with Ext JS, it was quite easy to learn. But now I just can't figure out the communication between JS and JSP. I have a tree in the UI and I like to load it with the database IDs from my table, under the database ID nodes I'd like to list all the schema names and under these nodes I'd like to list all the tables. For this I need to send the information from a JSP to JS. I've read a little about AJAX and JSON. But I don't really know where should I write my AJAX code (in the same source file where the onready() function is located or not?) or if JS can handle Java objects somehow. And how should I load the data in the tree?

I appreciate every suggestion!

Animal
27 Jul 2009, 3:56 AM
You have to seperate out the times of execution of the code.

There is the execution time of the JSP (which becomes a servlet inside the JEE container).

At this time, you will be manipulating the JDBC ResultSet object.

What the JSP writes out to the browser is fixed at that point.

So if this is not a single page application, but just a regular page which is navigated to and then away from, what you can do is just embed any data you want as a javascript literal.

Just write out Javascript assignment statements to set vars equal to the data.

And you serialize your Java objects into these literals using a JSON library (There are several for Java, I use an enhanced version of Crockford's classes)

g99
27 Jul 2009, 5:39 AM
Okay, I've found a good JSON library.
How can I pass the json string from the JSP to the JavaScript? As far as I know, the request.setAttribute(attr) is only for JSP to JSP communication.

EDIT:
Oh, it's obvious: with XMLHttpRequest.

Animal
27 Jul 2009, 6:05 AM
You could.

But if the data is known in the JSP at JSP execution time, you could just write the data into the page as a literal.