Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring@ModelAttribute接口_Java_Spring_Spring Mvc_Model View Controller_Spring Web - Fatal编程技术网

Java Spring@ModelAttribute接口

Java Spring@ModelAttribute接口,java,spring,spring-mvc,model-view-controller,spring-web,Java,Spring,Spring Mvc,Model View Controller,Spring Web,在下面的场景中,如何将接口设置为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 e

在下面的场景中,如何将接口设置为
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";
}
上面的代码片段给出了以下错误

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

我不想让spring为我实例化
实体
,我想使用
map提供的现有实例

解决办法是这样的

@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";
}

这里发生的情况是,
更新
中的
实体
绑定到从
@modeldattribute
注释的
实体
方法创建的
实体
。Spring然后将表单值应用于现有对象

您是否在视图侧找到了
实体
对象?Thymeleaf表单:
确定正确,并确保该实体类中的属性名称与
th:field
@JohanSjöberg是存储在会话中的实体?否则它将无法在请求/响应周期中生存。@Kayaman不,不是。很高兴知道。