【问题标题】:Using spring forms in templates在模板中使用弹簧表单
【发布时间】:2014-08-22 22:12:19
【问题描述】:

我的 header.jsp 中有一个注册表单,其中包含字段;姓名-电子邮件-密码。

当用户点击“注册”按钮时,它将被发布到我的注册控制器:

 @RequestMapping(value ="/register", method = RequestMethod.POST)
    public String registerUserAccount(@Valid @ModelAttribute("user") RegistrationForm userAccountData,
                                      BindingResult result, ... )

由于我使用的是 spring 表单标签,因此我在我的索引视图中包含了一个用于数据绑定的空用户对象。

问题是我不断得到

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

此表单位于我的头文件中,因此可以从所有页面访问。我是否必须为每个 ModelAndView 添加一个用户对象,或者有没有更简洁的方法来解决这个问题。

【问题讨论】:

    标签: spring spring-mvc sitemesh


    【解决方案1】:

    您可以执行以下操作:

    @ControllerAdvice
    public class ModelAdvice {
    
       @ModelAttribute
       public RegistrationForm registrationForm() {
         return new RegistrationForm();
       }
    
    }
    

    @ControllerAdvice 用于当您希望将某些内容应用于所有控制器时。在这种情况下,您想将@ModelAttribute 应用于所有控制器,因为正如您所说,注册表在所有页面中。

    要获得更多粒度控制,您可能希望实现一个HandlerInterceptor,以便在需要时将所需数据添加到HttpServletRequest

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多