开发者

JSP, JavaScript, and Java Objects

I have a JSP where I'm using a javascript framework to build a chart using the Google Visualization API.

My servlet is returning a sales hashmap object with year as the key and integer (sales number) as the value.

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

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

The sales object in my js gets the hashmap but it's a long string. Do I have to parse it 开发者_开发问答in my javascript or is there a way it will automatically put the hashmap object properly into the javascript sales object?


you wont need to use an external json library (but you could!) - you can print out the json directly into a javascript variable like:

<%@ 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>


Java and Javascript are completely different languages. Javascript doesn't know what do do with a Java HashMap object (actually in your example you'll get the output of HashMap.toString()). You'll have to serialize it into some form that Javascript will understand, eg. JSON.


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


All this piece of code

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

does is print the value of session.getAttribute("sales") to the HTML output. Without any logic on your part as to how to format the output, Java will merely call .toString() on that Object - which the default implementation (unless you override it) usually results in an output that looks like classname@1234abc12.

So the short answer is that yes you will need to put in some logic on the Java side as far as how you would like your object / data structure to be output into the HTML document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜