I want to pass a String from a Servlet to a jsp page, where it has to be passed on to a init function that resides in an external .js. That’s what I got so far:
servlet
request.setAttribute("jsonString", json.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("graph.jsp");
dispatcher.forward(request, response);
jsp
<body onload="init('<%= request.getParameter("jsonString") %>');">
js
function init(jsonString){
var json = jsonString;
Unfortunately the only thing I receive in the init function is null. I made sure that json.toString() returns the correct value. So it must get lost between the forwarding and the init function. What is the correct way to do this?
You are setting an attribute, but retrieving a parameter, which is not the same thing.
I think you should try expression language
You could also use
<%= request.getAttribute("jsonString") %>, but to me it is less readable, whereas EL is more concise.