Struts2的标签库中,有一个出场频度很高的逻辑标签---IF标签
<s:if>其实很简单, 就两个参数,常用的就一个"test"
参数如下:
名称 必需 默认 类型 描述
test 是 Boolean 决定标志里内容是否显示的表达式.else标志没有这个参数
id 否 Object/String 用来标识元素的id.在UI和表单中为HTML的id属性
但是, 要写一个合法test表达式,却是让我觉得很麻烦的事.( 经常写错)
test里面写的表达式经常要结合OGNL使用的, 例如:
<s:set name="name" value="<%= "'" + request.getParameter("name") + "'" %>" />
<s:if test="#name == 'Max'">
Max's file here
</s:if>
<s:elseif test="#name == 'Scott'">
Scott's file here
</s:elseif>
<s:else>
Other's file here
</s:else>
以上都是基本使用方式.
2.关于test表达式的flag右值
程序里经常有需要判断一个标志来控制页面元素的显示, 而这个传到页面的标志又是String型的"0"和"1", 表达式该怎么写?
<s:if test="#flag == '1">
display some info
</s:if>
你认为像上面这种写法OK吗? 自己试试吧.
正确的写法如下例:
<s:set name="pf" value="#attr.orderlist.paidflag" ></s:set>
<s:if test="#attr.orderlist.paidflag == \"1\"">
<span style="color: #CC0000;">
<STRONG><s:property value="%{'已付款'}" /></STRONG>
</span>
</s:if>
<s:else>
<span style="color: #00CC00;">
<STRONG><s:property value="%{'未付款'}" /></STRONG>
</span>
</s:else>
就是这种写法 \"1\" 使用转义字符, 当然这个例子的OGNL复杂了点,因为这段代码所处的环境的关系.但重点是这种写法!
引用1
If care is not taken with the quoting of literals, the expression language (OGNL) will misinterpret a char as a String.
===========================================
Wrong
<s:if test="aStringProperty == 'A'">
Why doesn't this work when myString is equal to A?
</s:if>
========================================================
The solution is simple: flip the double and single quotes.
Right
<s:if test='aStringProperty == "A"'>
This works!
</s:if>
Another solution is to escape the double quotes in the String.
Also Right
<s:if test="aStringProperty == \"A\"">
This works too!
</s:if>
引用2---一个兄弟的回帖
抱歉,经过再次分析,这不是struts2的bug。一个很容易错误应用的问题。
<s:if test="deptType==1" >下属 </s:if>如果你的数据库对应的字段类型为整形,可以这样使用;
<s:if test="deptType=='1'" >下属 </s:if>如果你的数据库对应的字段类型为char,可以这样使用;
<s:if test="deptType=='aa'" >下属 </s:if>如果你的数据库对应的字段类型为varchar,并且数据库中的字符串都是多余一个字符的字符串,可以这样使用;
<s:if test="deptType==\"1\"" >下属 </s:if> <s:else>直属 </s:else>(测试通过,这样用是最正确的)
3.test表达式中的OGNL
OGNL表达式中的#符号,该使用的时候,就一定不能省略,否则取不到值的. 除非你是取ValueStack中的东西可以不要.(取OGNL的Root里的东西本来就不用加#符号)
4.复杂逻辑的test表达式
不多说了, 给个例子就是了.
如果验证有错误的时候, 在页面显示出错误消息的例子:
<s:if test="fieldErrors!=null&&fieldErrors.size !=0">
<div id="ErrorArea" style="color: #CC0000; border: 1px solid #CC0000;">
<s:fielderror id="error"></s:fielderror></div>
</s:if>
标签的使用
最新推荐文章于 2020-05-20 02:21:28 发布