【问题标题】:Struts2 if tag not evaluatingStruts2 如果标签不评估
【发布时间】:2013-03-27 08:33:28
【问题描述】:

我有这段代码遍历某个对象集合,我想对每个元素执行类型检查(或instanceof)运算符。但是在我的<s:if> 上,它似乎没有进行评估。我错过了什么?

<s:iterator value = "myQuestions" var = "q"  status="key">

        <s:checkbox name="myQuestions[%{#key.index}].chosen" />
        <s:property value = "%{myQuestions[#key.index].question}"/> 

    <s:if test ="%{myQuestions[#key.index].getClass().simpleName} == 'Question'" > 
            THIS IS A QUESTION.
    </s:if> 


</s:iterator>

【问题讨论】:

  • 您在应用服务器中运行的是哪个 Java 版本?根据 API,getSimpleName 需要 Java 1.5 或更高版本
  • 我会强烈建议不要使用类类型作为视图层功能开关。当然,您可以以一种更清洁、更不脆弱的方式来做到这一点。
  • @DaveNewton 你有什么想法?
  • @user962206 不知道更多,我不知道。在一个列表中存储不同的对象类型通常是一种气味。你和他们有什么区别?答案?一个问题应该有答案——一个数据结构。

标签: jsp if-statement struts2 iterator ognl


【解决方案1】:

实现 if 循环功能的更好方法是在 Action 层上编写一个公共函数,该函数返回一个字符串值(类名)并将 Question 类型作为参数。一些相关的例子可能是这样的

public String getClassName(Ouestion question){
  if(question instanceof SomeDerivedQuestion){
    return "someDerivedQuestion";
  }
  //other code comes below
}

现在在 JSP 中你可以做这样的事情

<s:if test="%{getClassName(myQuestions[#key.index]).equals('someDerivedQuestion')}> 
  THIS IS A DERIVED QUESTION.
</s:if>

最好让 JSP 来处理应用程序的表示部分并覆盖 Java 服务器端所需的编码

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 2023-03-09
    • 1970-01-01
    • 2011-04-18
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2014-05-23
    相关资源
    最近更新 更多