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>