I\'m trying to figure out if there\'s any functional difference between these two uses of the JSTL
tag. Let\'s assume I have imported some string
Difference between jstl c:set value in attribute and body of tag
There is a technical difference.
The value
keeps the original value type. E.g., if you supplied Integer
or whatever, it will stay Integer
. The body, however, basically does a toString()
on the value and thus essentially converts any type to String
. This can be beneficial in some cases, e.g.:
Coming back to the concrete functional requirement, the first example will only work if you're targeting a Servlet 3.1 / EL 3.0 container (Tomcat 8, etc) with a webapp whose web.xml
matches Servlet 3.1.
<c:set var="SOME_VAR" value="${AppConstants.SOME_CONSTANT}" />
Namely, this is only supported since EL 3.0. This is definitely the preferred approach over the Scriptlet way. You should try to avoid Scriptlets at all cost. You only need to keep in mind that the code is not backwards compatible with older versioned target runtimes.
According to O'Reillys HeadsFirstServlets pg 457, why would you use the body version of c:set instead of the no-body version. It looks like they do the same thing.
Answer:
That’s because they DO... do the same thing. The body version is just for convenience when you want more room for the value. It might be a long and complex expression, for example, and putting it in the body makes it easier to read.
Update
After some additional research it turns out the above reasoning pertains only to EL v2.2 and lower. See the answer by BalusC for 3.0 behavior.