Difference between specifying JSTL value via attribute and body

前端 未结 2 623
孤独总比滥情好
孤独总比滥情好 2021-01-15 02:41

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

相关标签:
2条回答
  • 2021-01-15 02:55

    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.:

    • Convert integer value to string using JSTL/EL
    • How to find length of an integer in JSP?
    • How to check isNumeric/IsNumber in JSTL
    • how to get the base url from jsp request object?

    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.

    See also:

    • How to reference constants in EL?
    • How to avoid Java code in JSP files?
    0 讨论(0)
  • 2021-01-15 03:17

    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.

    0 讨论(0)
提交回复
热议问题