Spring MVC 3 ModelAndView:控制器方法返回多个视图

时间:2013-06-12 17:33:31

标签: spring-mvc modelandview

我的要求是根据所选值(选择表格)返回视图

view.jsp的:

      <form  method="post" action="/aaa">
                      <select id="attr1" name="attr1">

                            <option value="1">A</option>
                            <option value="2">B</option>

                        </select>
                  <input type="submit" value="submit" />
</form>

如果选择的值是A(1),则view1是要显示的视图,否则显示view2。

控制器方法:

@RequestMapping(value = "/aaa", method = RequestMethod.POST)
public ModelAndview methodName ( HttpServletRequest request,
        HttpServletResponse response){

   attribute=request.getParameter("attr1");

   if (attribute==1) return new ModelAndView("view1")
   else if (attribute==2) return new ModelAndView ("view2")

   }

我该怎么办? 感谢。

1 个答案:

答案 0 :(得分:1)

完全可以使用多个视图。

考虑HTML:

<select id="attr1" name="attr1">
    <option value="1">A</option>
    <option value="2">B</option>
</select>

然后控制器方法应该是:

@RequestMapping(value = "/aaa", method = RequestMethod.POST)
public ModelAndView methodName(@RequestParam(value = "attr1") int attribute) {
    if (attribute == 1) {
        return new ModelAndView("view1");
    }
    else if (attribute == 2) {
        return new ModelAndView("view2");
    }
    else {
        return null; // Empty 200 OK just to be sure if other attr is received
    }
}