- 1 min read

JSP: Passing Variable Data to JavaScript

img of JSP: Passing Variable Data to JavaScript

When you try to marry old JSP Technology with the modern wonders of Typescript/ES6. You will want to expose some data provided by the backend into the Javascript. If you have the possibility you would use a fetch() call to receive JSON. Sometimes, it is not possible to do a big rewrite of the JSP to fix a minor bug. Here is a very dirty way to pass data from the JSP into the JS code. This code will utilize the HTML5 data-attribute. Learn more about it here

JSP File:

<fmt:message var="someText" key="core.someText" />

<div id="jsVariables" data-someText="${self.someText}"></div>


let dataContainer = document.getElementById('jsVariables')
let someText = dataContainer.dataset.someText


let someText = $('#jsVariables').data('someText')

This is a very elegant solution (for well I guess using JSPs), now you can run ESLint on your Javascript Code and will not have any unresolved variables.