使用多个modelAttributes从JSP接收2个对象

时间:2015-01-26 09:28:16

标签: java spring spring-mvc

我正在开发一个Spring-MVC应用程序,其中有两个部分。它基本上是一个带有2种模式的应用笔记,一种是groupMode,另一种是personalMode。现在他们在后端都有不同的dao,serviceImpl,但它们在一个控制器视图中。

我有一个布尔值来设置,以了解用户当前所处的模式,以在特定数据库表中执行CRUD操作。现在由于两种组模式都是个人模式在同一视图中,我必须制作我的方法,以便他们可以接受任何一种模式的对象。即使我在模型属性中声明2,spring也支持只接受一个对象。以下是我想要实现的例子:

  @RequestMapping(value = "/section/add", method = RequestMethod.POST)
    public
    @ResponseBody
    boolean addSection(@ModelAttribute("section") Section section, @ModelAttribute("groupsection") GroupSection groupSection,Model model) {
       if(boolean == true){
       this.groupSectionService.addGroupSection(groupSection);
       model.addAttribute("groupsection", new GroupSection());
     } else{
       this.sectionService.addSection(section);
        model.addAttribute("section", new Section());
       }
        return true;
    }

这可能,我将始终从前端发送一个对象。非常感谢。欢迎任何指示或建议。

1 个答案:

答案 0 :(得分:2)

每当有if这样的陈述时,"分裂"完整的控制器方法,和你的一样,我觉得一个控制器方法应该用两种方法替换,每种方法一种。

最简单,最直接的解决方案是使用两个不同的网址。

但是也许你有一些理由使用相同的网址,那么我会有两种不同的控制器方法使用相同的网址但params

中的@RequestMapping属性不同
@RequestMapping(value = "/section/add",
                method = RequestMethod.POST
                params="createGroupSection=false")
@ResponseBody
public boolean addSection(@ModelAttribute("section") Section section) {...}

@RequestMapping(value = "/section/add",
                method = RequestMethod.POST
                params="createGroupSection=true")
@ResponseBody
public boolean addGroupSection(@ModelAttribute("section") Section section) {...}
相关问题