【问题标题】:Migrating to Spring MVC 4迁移到 Spring MVC 4
【发布时间】:2014-06-03 14:15:01
【问题描述】:

我们正在将 mvc 代码迁移到 Spring 4。之前我们有一个方法 formBackingObject,我们将其转换为获取方法 initForm。 但问题是 - 在扩展 SimpleFormController 的先前控制器中,formBackingObject 甚至在提交方法之前就被调用了。我们现在已经删除了 SimpleFormController。但是 initForm 在页面加载时只被调用一次。在提交之前不会调用它。还有一些创建用户对象和添加到 UserProfileForm 对象的自定义逻辑。

你有没有遇到过类似的问题。

旧代码

    protected Object formBackingObject(HttpServletRequest request) throws Exception {       
    final UserProfileForm userProfileForm = new UserProfileForm();
    final String id = request.getParameter("id");
    if (id != null && !id.trim().equals("")) {
        final User user = authenticationServices.findUser(ServletRequestUtils.getLongParameter(request, "id"));
        userProfileForm.setUser(user);
    } else {
        final User user = new User();
        userProfileForm.setUser(user);
    }
    return userProfileForm;
}

新代码

@RequestMapping(method = RequestMethod.GET)
public String initForm(HttpServletRequest request, ModelMap model) throws Exception{
    final UserProfileForm userProfileForm = new UserProfileForm();
    final String id = request.getParameter("id");
    if (id != null && !id.trim().equals("")) {
        final User user = authenticationServices.findUser(ServletRequestUtils.getLongParameter(request, "id"));
        userProfileForm.setUser(user);
    } else {
        final User user = new User();
        userProfileForm.setUser(user);
    }
    addToModel(request, model);
    model.addAttribute("userProfileForm", userProfileForm);
    return "user-management/user-profile";
}

【问题讨论】:

  • 您可能应该考虑使用带有 @ModelAttribute 注释的方法

标签: spring model-view-controller


【解决方案1】:

创建一个带有 @ModelAttribute 注释的方法来填充您的模型。

@ModelAttribute("userProfileForm");
public UserProfileForm formBackingObject(@RequestParam(value="id", required=false) Long id) throws Exception{
    final UserProfileForm userProfileForm = new UserProfileForm();
    if (id != null) {
        final User user = authenticationServices.findUser(id);
        userProfileForm.setUser(user);
    } else {
        final User user = new User();
        userProfileForm.setUser(user);
    }
    return userProfileForm; 
}

@RequestMapping(method = RequestMethod.GET)
public String initForm() {
    return "user-management/user-profile";
}

这样你也可以使用@RequestParam注解,而不是自己拉出参数。

有关该主题的更多信息,请参阅the reference guide

【讨论】:

    【解决方案2】:

    某些模块间依赖关系现在在 Maven POM 级别是可选的,它们曾经是必需的。比如 spring-tx 及其对 spring-context 的依赖。对于一直依赖传递依赖管理来拉入受影响的下游 spring-* 的用户,这可能会导致 ClassNotFoundErrors 或其他类似问题。要解决此问题,只需将适当的缺失 jar 添加到您的构建配置中。

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 2017-02-05
      • 2017-05-30
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多