java form model_java – Spring MVC:在表单处理操作中有多个@ModelAttribute

上下文

我在两个实体之间有一个简单的关联 – 类别和电子邮件(NtoM).我正在尝试创建用于浏览和管理它们的Web界面.要浏览类别并将电子邮件添加到该类别中,我使用带有类别ID(UUID)的@RequestMapping包装的控制器,因此所有控制器操作始终在使用path指定的类别的上下文中进行.

我使用@ModelAttribute为整个控制器范围预加载上下文类别.

问题

这种方法适用于列表和显示表单.但是它在表单提交时失败 – 在稍微调试之后,我发现表单数据会覆盖我的类别@ModelAttribute参数.

在我的代码中,在方法save()中,类别实际上并不是使用addCategory()方法加载的模型属性,而是填充了表单数据(电子邮件模型也已填充,这是正确的).

我正在寻找能够将表单数据仅绑定到特定的@ModelAttribute的解决方案.

我在Spring MVC文档中读到了参数的顺序很重要,但是我根据示例对它们进行了相应的排序,但它仍然没有像预期的那样工作.

代码

这是我的控制器:

@Controller

@RequestMapping("/emails/{categoryId}")

public class EmailsController

{

@ModelAttribute("category")

public Category addCategory(@PathVariable UUID categoryId)

{

return this.categoryService.getCategory(categoryId);

}

@InitBinder

public void initBinder(WebDataBinder binder)

{

binder.registerCustomEditor(Set.class, "categories", new CategoriesSetEditor(this.categoryService));

}

@RequestMapping(value = "/create", method = RequestMethod.GET)

public String createForm(@ModelAttribute Category category, Model model)

{

// here everything works, as there is just a single @ModelAttribute

return "emails/form";

}

@RequestMapping(value = "/save", method = RequestMethod.POST)

public String save(

@ModelAttribute @Valid Email email,

BindingResult result,

Model model,

@ModelAttribute("category") Category category

) {

// saving entity, etc

// HERE! problem is, that response is bound BOTH to `email' and `category' model attributes

// and overrides category loaded in `addCategory()' method

return String.format("redirect:/emails/%s/", category.getId().toString());

}

}

以防万一这里也是表单代码:

:

:

:

注意:我不希望多个@ModelAttributes来自POST,只是想以某种方式区分表单模型与先前生成的属性.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值