JSP, JavaScript, and Java Objects

I'm new to JSP, so naked with me. I have a JSP where I use a javascript structure to build a chart using the Google visualization API.

My servlet returns a hashmap sales object with a year as a key and an integer (sales number) as a value.

My javascript uses a sales object to add data to the Google chart API, which builds my chart. the code:

sales = '<%= session.getAttribute("sales") %>'; 

The sales object in my js gets a hashmap, but this is a long string. Should I parse it in my javascript or is there a way in which it will automatically place the hashmap object in the javascript sales object?

+6
java javascript jsp servlets
source share
4 answers

you do not need to use an external json library (but you could!) - you can print json directly in a javascript variable, for example:

 <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <script> (function(){ var sales = { <c:forEach var="entry" items="${requestScope['sales'].entrySet}" varStatus="counter"> '${entry.key}' : ${entry.value} //outputs "2000" :1234 , <c:if test="${!counter.last}">, </c:test> </c:foreach> }; //js code that uses the sales object doStuffWith(sales); })() </script> 
+4
source share

Java and Javascript are completely different languages. Javascript does not know what to do with the Java HashMap object (in fact, in your example you will get the output of HashMap.toString ()). You will have to serialize it in some form that Javascript will understand, for example. JSON

+2
source share

Try using JSON , which will allow you to describe your Java object in json (java script object notation) This way you can load the described object directly into javascript.

+1
source share

All this piece of code

 sales = '<%= session.getAttribute("sales") %>'; 

this outputs the value of session.getAttribute("sales") to the HTML output. Without any logic on your part regarding how to format the output, Java will simply call .toString() on this object, which by default (unless you override it) will usually produce output that looks like classname@1234abc12 .

So the short answer is: yes, you will need to add some logic on the Java side, as far as you want the object / data structure to be output to the HTML document.

0
source share

All Articles