Struts 2 and Spring with EL - What are the differe

2019-07-18 06:10发布

问题:

This question already has an answer here:

  • what's the difference between #{} ${} and %{}? 2 answers

I am obliviously new to EL (with Struts 2 specifically). I am updating the current code and I see different types of entries. Whats the difference?

<s:property value="%{obj.field}"/>  // With %{}
<s:property value="obj.field"/>     // Without %{}
<s:property value="%{#obj.field}"/> // with %{} and prefixed # 
${obj.field}  // with ${}
// any other types I may have missed... 

回答1:

That's not JSTL, that's OGNL. When inside a Struts tag,

%{} means you are forcing the evaluation of an expression. Most of the time it's useless, because the evaluation is automatic, but it can be put for consistency, to clear the fact that an evaluation is in progress.

%{foo} means you are accessing the foo object in the ValueStack (eg. an Action property).

%{#foo} means you are accessing the foo object that is in the ActionContext, but not in the ValueStack.

Read more in this great answer.

${foo} is JSP EL (Expression Language).

JSTL is a different library and uses its proprietary tags, like <c:forEach>, <c:out />, <c:when> and so on.

You can mix JSTL and OGNL, btw.

When using Struts2, you usually use OGNL and Struts tags (but nothing prevent you to use JSTL, if you want). When using Spring MVC, you use JSTL only.

EL can always be used when dealing with JSP, but it has some drawbacks, and needs some tuning with Struts2.