Access Java / Servlet / JSP / JSTL / EL variables in JavaScript

Viewed 44004

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?

5 Answers

In JSP file:

<head>
...
<%@ page import="com.common.Constants" %>
...
</head>
<script type="text/javascript"> 
        var constant = "<%=Constants.CONSTANT%>"
</script>

This constant variable will be then available to .js files that are declared after the above code.

Constants.java is a java file containing a static constant named CONSTANT.

The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.

Passing JSON from JSP to Javascript.

I came here looking for this, @BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.

<script id="jsonData" type="application/json">${jsonFromJava}</script>

and in the JS:

var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);

In JSP page :

<c:set var="list_size" value="${list1.size() }"></c:set>

Access this value in Javascipt page using :

var list_size = parseInt($('#list_size').val());

I added javascript page in my project externally.

Related