如何使用相应的提交操作在一个页面中处理两个弹簧形式?

时间:2015-12-18 10:32:36

标签: spring-mvc spring-form

我在一个页面上有两个弹簧形式,并有自己的提交操作:

JSP:

<form:form id="frm_user_login" class="animated fadeIn" method="post" action="./loginsubmit.htm" commandName="useSignInFm">

<form:form id="frm_user_register" class="animated fadeIn" method="post" action="./registersubmit.htm" commandName="userRegistrationForm">

他们各自在一个控制器中的映射:

位指示:

@RequestMapping(value = "/loginsubmit.htm", method = RequestMethod.POST)
public ModelAndView signIn(@ModelAttribute("useSignInFm") SignInForm signInForm, BindingResult bindingResult,
        Model model, HttpServletRequest request)

@RequestMapping(value = "/registersubmit.htm", method = RequestMethod.POST)
public ModelAndView userRegistration(@ModelAttribute("userRegistrationForm") UserRegistrationForm userRegistrationFm, 
        BindingResult bindingResult,Model model, HttpServletRequest request)

提交一个表单(userRegistrationForm)会提供其他表单的例外:

Neither BindingResult nor plain target object for bean name 'useSignInFm' available as request attribute.

我该如何处理?

2 个答案:

答案 0 :(得分:0)

由于要在一页中呈现两个表单,因此需要将两个表单都绑定到控制器映射中,否则未绑定的表单将在返回视图时丢失,从而导致该错误。呈现视图时,表单支持对象必须同时存在。

所以尝试一下,它在我的情况下很有效,与您的情况非常相似:

@RequestMapping(value = "/loginsubmit.htm", method = RequestMethod.POST)
public ModelAndView signIn(@Valid @ModelAttribute("useSignInFm") SignInForm signInForm, 
BindingResult bindingResult, @ModelAttribute("userRegistrationForm") 
UserRegistrationForm userRegistrationFm, Model model, HttpServletRequest request)

@RequestMapping(value = "/registersubmit.htm", method = RequestMethod.POST)
public ModelAndView userRegistration(@Valid @ModelAttribute("userRegistrationForm") 
UserRegistrationForm userRegistrationFm, BindingResult bindingResult,
@ModelAttribute("useSignInFm") SignInForm signInForm, Model model, HttpServletRequest request)

请注意,我添加了@Valid注释,因为我假设您想验证每个请求映射中的第一个表单。还应注意bindingResult参数的位置:它必须紧跟要考虑其绑定结果的@ModelAttribute参数。

答案 1 :(得分:-1)

  

BindingResult和bean名称'useSignInFm'的普通目标对象都不可用作请求属性

表示没有id / name匹配“useSignInFm”的元素。你应该先开始修复它。