How to add a condition in Struts iterator tag?

耗尽温柔 提交于 2020-01-15 13:33:45

问题


I want to highlight a row when the value of rating is less than or equal to 2. I am not able to use the <s:if> to get my result. Please tell me how to put condition in my JSP page.

<table>
<s:iterator value="fb" status="abc">
<s:if test="#abc.rating==2">
<td style="background: #CCCCCC">
</s:if>

<tr>
<td><s:property value="cid"/></td>
<td><s:property value="cname"/></td>
<td><s:property value="rating"/></td>
<td><s:property value="likes"/></td>
<td><s:property value="dislikes"/></td>
<td><s:property value="suggestion"/></td>
</tr>

</s:iterator>
</table>

回答1:


Suppose rating is a property of the object being iterated. Then inside the iterator tag you can access it by property name.

<s:if test="rating==2">
 <s:set var="myStyle" value="'background: #CCCCCC'"/>
</s:if>
<s:else>
 <s:set var="myStyle" value="'background: #FFFFFF'"/> 
</s:else>

then use HTML style attribute

<td style="<s:property value='#myStyle'/>">



回答2:


There are several ways:

  1. property name:

    <s:iterator value="mySource">
        <s:if test="rating==2">
    
  2. var alias reference:

    <s:iterator value="mySource" var="myVar">
        <s:if test="#myVar.rating==2">
    
  3. IteratorStatus index:

    <s:iterator value="mySource" status="myStat">
        <s:if test="mySource[%{#myStat.index}].rating==2">
    
  4. top reference:

    <s:iterator value="mySource">
        <s:if test="top.rating==2">
    



回答3:


You can use EL (expression language) like this

<td style="background: ${abc.rating<=2 ? '#CCCCCC' : ''}">

or you can define bean variable

<logic:lessEqual value="2" name="abc" property="rating">
  <bean:define id="colorTd" value="#CCCCCC"/>
</logic:lessEqual>

<td style="background: ${colorTd}">



回答4:


you have to use test="%{abc.rating==2}" like this instead of test="#abc.rating==2"

<table>
<s:iterator value="fb" status="abc">
<s:if test="%{abc.rating==2}">
<td style="background: #CCCCCC">
</s:if>

<tr>
<td><s:property value="cid"/></td>
<td><s:property value="cname"/></td>
<td><s:property value="rating"/></td>
<td><s:property value="likes"/></td>
<td><s:property value="dislikes"/></td>
<td><s:property value="suggestion"/></td>
</tr>

</s:iterator>
</table>


来源:https://stackoverflow.com/questions/21064377/how-to-add-a-condition-in-struts-iterator-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!