Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  109] [ 1]  / answers: 1 / hits: 22052  / 10 Years ago, tue, april 15, 2014, 12:00:00

I'm working on the project that requires reading database in JSP, but the data is used by javascript to render the google map(the map points). I don't know how to access the NoSQL database by javascript, so I'm thinking about embed JSP in javascript to access the data and as a way to feed them to javascript.



I've searched a lot about these features, I'd like to have code like:



var a = <%=data %>


How could I control the script(since it's .js), and index.jsp ?



Thanks


More From » html

 Answers
35

Java code runs on server, this means, it runs on your application server and helps to render the view (in this case, the JSP). JavaScript runs on client side, this means, it runs on the client browser (Internet Explorer [ugh], Firefox, Chrome, and on...). So, based from your current code:



var a = <%=data %>;


Assuming data is a String and has a value of Hello World, the generated HTML/JS would be:



var a = Hello World;


Which will produce an error. So, you would need to quote the variable:



var a = '<%=data %>';


Now this will produce:



var a = 'Hello World';





For more complex communication, like passing a list or a complex structure or a list of complex structures from server to client, it would be better using a common format to exchange data like JSON. You can marshall the data to JSON string from server (preferably in a Servlet) and then pass it to JavaScript side easily. For example, using Jackson Library for Java:



@WebServlet(/MyServlet)
public class MyServlet extends HttpServlet {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
List<ComplexObject> complexObjectList = ... //get your data
request.setAttribute(complexObjectList, OBJECT_MAPPER.writeValueAsString(complexObjectList));
//forward to the desired view...
request.getRequestDispatcher(/WEB-INF/theView.jsp).forward(request, response);
}
}


Then in your JSP (using Expression Language because you should avoid using scriptlets):



<script type=text/javascript>
var complexObjectList = JSON.parse('${complexObjectList}');
//play with your new object in JavaScript side...
</script>

[#71452] Monday, April 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
efren

Total Points: 186
Total Questions: 85
Total Answers: 112

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;