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不,不是。很高兴知道。