Spring MVC 3 ModelAndView: controller method to return several views

RaisMEd picture RaisMEd · Jun 12, 2013 · Viewed 7.9k times · Source

my requirement is to return view according to the selected value (select form)

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>

if the value selected is A(1) is selected, view1 is the view to display, else view2 is displayed.

Controller method:

@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")

   }

How can I do it? Thanks.

Answer

acdcjunior picture acdcjunior · Jun 12, 2013

Multiple views are perfectly possible.

Considering the HTML:

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

Then the controller method should be:

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