【问题标题】:Spring @ModelAttribute interfaceSpring @ModelAttribute 接口
【发布时间】:2017-02-23 20:52:47
【问题描述】:

我怎样才能有一个接口作为ModelAttribute 在下面的场景中?

@GetMapping("/{id}")
public String get(@PathVariable String id, ModelMap map) {
  map.put("entity", service.getById(id));
  return "view";
}

@PostMapping("/{id}")
public String update(@ModelAttribute("entity") Entity entity) {
  service.store(entity);
  return "view";
}

sn-p 上面给出以下错误

BeanInstantiationException: Failed to instantiate [foo.Entity]: Specified class is an interface

我不想让spring为我实例化entity,我想使用map.put("entity", ..)提供的现有实例。

【问题讨论】:

  • 你有没有在视图侧感觉entity对象?
  • 百里香形式:<form th:object="${entity}">..</form>
  • 好的,这是正确的,并确保您在该实体类中的属性名称与th:field 相同
  • @JohanSjöberg 实体是否存储在会话中?否则它将无法在请求/响应周期中存活。
  • @Kayaman 不,不是。很高兴知道。

标签: java spring spring-mvc model-view-controller spring-web


【解决方案1】:

正如 cmets 中所指出的,Entity 实例在 getpost 请求之间无法生存。

解决办法是这样的

@ModelAttribute("entity")
public Entity entity(@PathVariable String id) {
    return service.getById(id);
}

@GetMapping("/{id}")
public String get() {
   return "view";
}

@PostMapping("/{id})
public String update(@ModelAttribute("entity") Entity entity) {
  service.store(entity);
  return "view";
}

这里发生的是update 中的Entity 绑定到从@ModelAttribute 注释的entity 方法创建的Entity。然后 Spring 将表单值应用于现有对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 2014-12-20
    • 1970-01-01
    • 2014-09-20
    • 2021-12-14
    • 1970-01-01
    • 2017-11-27
    相关资源
    最近更新 更多