【问题标题】:Spring: How do I construct this command object through a GET HTTP request?Spring:如何通过 GET HTTP 请求构造这个命令对象?
【发布时间】:2012-04-11 17:04:11
【问题描述】:

我正在使用 Spring 3.1.0.RELEASE 和 Hibernate 4.0.1.Final。我想在控制器中调用一个搜索方法,该方法将搜索 bean(下面的事件 bean)作为输入......

@RequestMapping(value = "/search_results.jsp")
public ModelAndView processSearch(final HttpServletRequest request, final Event searchBean, final BindingResult result) {
    ...
}

事件 bean 包含以下字段 ...

@Entity
@Table(name = "EVENTS")
public class Event implements Comparable {

    ...
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="EVENT_FEED_ID")
    private EventFeed eventFeed;
    ...
}

其中 EventFeed 对象包含以下字段...

@Entity
@Table(name = "EVENT_FEEDS")
public class EventFeed {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    @NotEmpty
    @Column(name = "TITLE")
    private String title;

    ... 
}

如何构造一个 URL 以填充搜索 bean 的 Event.getEventFeed().getId() 字段?

我意识到我可以使用“eventFeedId=2”之类的参数提交 GET 请求并手动填充所有内容,但由于其他页面正在提交填充命令对象的请求,我想继续使用相同的逻辑。

【问题讨论】:

  • "... 手动填充所有内容,但由于其他页面正在提交填充命令对象的请求”是您的问题:“我如何从数据库中加载 EventFeed?” ? -- 如果您还有其他问题,能否请您更准确地提出问题:因为您的正式问题的答案是?event.eventFeed.id=1&event.eventFeed.title=hallo - 但我认为这不是您想知道的。
  • 是的,“?event.eventFeed.id=1&event.eventFeed.title=hallo”是我想知道的,除了我在下面指出的,我试过了,Event.getEventFeed() bean 没有被填充。

标签: spring search command-objects


【解决方案1】:

应该是

/search_results.jsp?event.eventFeed.id=...&event.eventFeed.title=...

event@ModelAttribute中定义的默认模型属性名称,其他绑定规则在5.4.1 Setting and getting basic and nested properties中描述。

但是请注意,如果您稍后将这些 bean 与 Hibernate 会话相关联,这种方法可能会导致问题。例如,如果您想通过调用merge() 将新的Event 附加到现有的EventFeed,它也会覆盖title 属性。因此,在这种情况下,最好避免过度使用数据绑定,而是将原语作为参数传递。

【讨论】:

  • 我尝试了您建议的查询字符串,但 Event bean 的 EventFeed 字段仍然为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2021-12-16
  • 2011-05-12
  • 1970-01-01
  • 2013-02-24
  • 2012-10-21
相关资源
最近更新 更多