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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With