and then access that va...">

Jstl inside javascript

Is it possible to use jstl inside javascript?

I bind to setting <c:set var="abc" value="yes"/>

and then access that value in html and execute some code. My problem is that c: set is always executed, even if the javascript condition is false.

 <script type="text/javascript"> var v1 = false; <c:set var"abc" value="yes"/> if(v1){ <c:set var"abc" value="no"/> } </script> 

In the above code, even if v1 is false, "no" sets the value to abc.

+7
javascript html jsp jstl
source share
3 answers

It makes no sense to be โ€œinside Javascriptโ€ when you are talking about server side JSP interpretation. There is simply no such thing as Javascript regarding this domain.

So yes, maybe if you mean you want to do something like

 var something = '${abc}'; 

Please note that you must be careful with quotes and special characters. The JSTL function fn:escapeXml() useless when you interpolate the JSP variable into the part of the page that will be interpreted by the browser as a Javascript source. You can use the JSON library to encode your strings, or you can write your own EL function to do this.

+18
source share

This is a pretty old thread, but this is the one I came across when I had the same problem. Since I thought about the solution myself, I will post it here if it helps someone in the future.

An html (or jsp) file looks for text inside an external file declared as a javascript source.

Tomcat (or similar) only interprets JSTL tags in files with the .jsp extension (or perhaps some others), but it does not matter for this answer.

So rename your .js file to give it a .jsp extension (e.g. javascript.js for javascript_js.jsp)

Add these lines at the top of javascript_js.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

and just leave the code unchanged.

Obviously, you also need to add more prefixes if you are using something other than c in the header:

If you use Eclipse (you donโ€™t know about other IDEs), it will assume that it is not a javascript file and you lose the color scheme for different keywords (var, function, etc.), var auto auto completion and auto indentation.

To trick the IDE, you can add

 // <script> 

as a js comment, before the actual code (after the declarations "<% @") and

 // </script> 

at the end of the file, again as a js comment.

It worked for me.

+4
source share
 <script> <c:set var="myVal" value="Hello"/> var val1="${myVal}"; </script> 
+3
source share

All Articles