【问题标题】:Get it in action but no display in s:iterator tag开始行动,但在 s:iterator 标记中不显示
【发布时间】:2013-04-07 06:22:40
【问题描述】:

我用

<class name="Topic" table="topic">     
         .......
  <set name="replies" inverse="true" lazy="false"  cascade="save-update">
        <key column="TOPIC_ID"/>
        <one-to-many class="Reply"/>
  </set>
</class>

我看到回复不为空,并且在topic.replies 中有元素;

Topic topic = topicService.getTopicById(topicId);
ActionContext actionContext = getActionContext();
actionContext.put("topic", topic);

在 JSP 中:

<s:iterator value="#topic.replies">
  <s:property value="title"/>
</s:iterator>

没有标题显示。 然后我改变我的代码

Topic topic = topicService.getTopicById(topicId);
ActionContext actionContext = getActionContext();
actionContext.put("replies", topic.getReplies);

在 JSP 中

<s:iterator value="#replies">
  <s:property value="title"/>
</s:iterator>

显示title的值。

我不知道为什么标题没有以第一种方式显示。

【问题讨论】:

    标签: java hibernate jsp struts2 actioncontext


    【解决方案1】:

    回复被配置为惰性,因此在您调用 topic.getReplies 之前它们不可用。这实际上是通过访问实体的代理来初始化惰性集合。另一方面,您尝试使用 OGNL 访问实体并以其他方式找到它,因此未初始化集合。

    【讨论】:

    • 非常感谢。但是我确实配置了lazy="false",即使我调用了topic.getReplies方法,jsp中也没有显示#topic.replies的标题。
    • @user2245634 topic.getReplies 应该与主题在同一个会话中调用,否则你会得到lazyInitializationException。
    【解决方案2】:

    你为什么要这样使用 ActionContext ?

    ActionContext 对于从其他地方(例如 Helper 类)访问数据(Action 已经可用)很有用,而无需传递任何参数。

    来自文档:What is the ActionContext

    为了保持签名的简短和有用的方法,该框架使用了两种技术:依赖注入线程本地,这两种技术又依赖于ActionContext.

    从 Struts 2 应用程序中的任何地方,您可以通过调用获得对 [ActionContext] 的引用

      ActionContext context = ActionContext.getContext();
    

    例如,如果从Action调用了一个helper类,如果它恰好需要访问ServletContext(可能是在写文件,需要ServletContext来获取它的路径),那么helper可以直接获取ActionContext .不需要从 Action 传递任何内容。

    JSP 属性通常是从Action 中读取的,Action 必须通过访问器(或getter)暴露这些属性;只需将 Hibernate 结果映射到 Action 中的某个 DTO。

    【讨论】:

    • 没错,在action不可用的地方使用action context和servlet action context。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多