Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 920
asdfasdf Avatar asked Oct 15 '09 20:10

asdfasdf


People also ask

Is JSP and JavaScript the same?

JavaScript and JSON differences JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null . It is based upon JavaScript syntax, but is distinct from JavaScript: most of JavaScript is not JSON. For example: Objects and Arrays.

What is JS and JSP in Java?

<script type= "text/javascript" > document.write( "Hello Geeks, Greetings from GeeksforGeeks" ) </script> JSP stands for Java Server Pages, are a dynamic web technology based on servlet container and Java EE specification which is used to generate dynamic web content in webpages.

Can you use JavaScript with JSP?

Yes, We can use javaScript with JSP page. As we know that javaScript is a Client-side script and JSP is a Server-side so we can attach a form validation to a JSP page to redirect HTML page and javaScript content. -Before submitting page to web server, it should be validate HTML field data.

Is there a difference between JavaScript and Java?

Key differences between Java and JavaScript: Java is an OOP programming language while Java Script is an OOP scripting language. Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only. Java code needs to be compiled while JavaScript code are all in text.


1 Answers

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>
like image 181
Chii Avatar answered Sep 30 '22 04:09

Chii