Reputation: 725
I am working on a project with Spring MVC with java as the backend and HTML(JSP)/CSS/JS as the frontend. In my controller in java I am adding data to the model like this
model.addAttribute("someData", theData);
which I can easily access in the JSP file like this
${theData} or "${theData}"
The problem for me is that this only works in my JSP file. I am importing other css and js files there like
<script src="<c:url value='/resources/javascript/main.js'/>"></script>
and they seem to have no access to the model. I understand that there is no model at runtime on the clientside, but the javascript files are served by the server the same way as the HTML/JSP file, so why does this not work? Or is there any kind of setting I have to use?
I realize that inline js code in my JSP file works, but this is not very flexible and just not a "real" solution for me. Also I would like to avoid additional calls to the server (like AJAX) to get my data.
Thanks for your help!
Upvotes: 0
Views: 799
Reputation: 725
I have "solved" it now by defining the databinding inline in the html document
var theData = "{theData}";
and then using that in my standard javascript file. Not really perfect but seems to be the best working solution.
Upvotes: 0
Reputation: 28519
willOEM gave you a good background. So static files don't know about the model values, but also there's no need for this as you can always code your way out.
If you're calling any function from your main.js
within your jsp, than at that point you should use the ${theData}
as a function argument. If not, you can always use a data attribute on a dom element, store your model variable there, and access it inside your js file, so something like
<div data-the-data="${theData}">Lorem ipsum</div>
Upvotes: 1
Reputation: 7169
...but the javascript files are served by the server the same way as the HTML/JSP file...
No, this is not true. The static JavaScript, CSS, and HTML files are being served by the web server as-is, with no processing. The EL snippet in your example...
<script src="<c:url value='/resources/javascript/main.js'/>"></script>
...is only generating a concrete URL based upon the relative URL that you have provided as an argument to the function. There is no knowledge embedded of what main.js
is or does. Your JSP files are explicitly processed by the Java servlet container. This is why it has knowledge about your application, beans, models, and all. This is a gross oversimplification, but hopefully it gets the point across.
Edit
You can use JSON from static files in your JSP, but you have to read, process, and store them as Java objects in a bean in your application. I am not sure why you would want to do this, though, since it is so easy to read JSON data via JavaScript.
Upvotes: 2