spring启动应用程序:使用@modeldattribute的nullpointerexception

ni65a41a  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(297)

我得到一个 NullPointerException 在这些 @ModelAttribute 变量。
这是我的密码:

@RequestMapping(value="/newUser", method=RequestMethod.POST)
public String newUser(@Validated @ModelAttribute("user") User user, BindingResult userBindingResult, @Validated @ModelAttribute("credentials") Credentials credentials, BindingResult credentialsBindingResult, @Validated @ModelAttribute("contacts") Contacts contacts, BindingResult contactsBindingResult, @Validated @ModelAttribute("address") Address address, BindingResult addressBindingRusult, Model model) {

    this.userValidator.validate(user, userBindingResult);
    this.credentialsValidator.validate(credentials, credentialsBindingResult);
    this.contactsValidator.validate(contacts, contactsBindingResult);
    this.addressValidator.validate(address, addressBindingRusult);

    if (!userBindingResult.hasErrors() && !credentialsBindingResult.hasErrors() && !contactsBindingResult.hasErrors() && !addressBindingRusult.hasErrors()) {

        user.setContacts(contacts);
        user.setAddress(address);
        credentials.setUser(user);
        credentials.setRole(Credentials.DEFAULT_ROLE);
        credentials.setPassword(passwordEncoder.encode(credentials.getPassword()));
        credentials.setEnabled(true); 
        credentialsService.saveCredentials(credentials);

        return "redirect:/dashboard?successUser";

    } else {
        return "redirect:/dashboard?errorUser";
    }
}

在加载页面时,我在前面的get方法中向模型添加了这些属性,并在chrome控制台中检查了表单发送的数据。下面是get方法的部分代码:

@RequestMapping(value= {"/dashboard"}, method= RequestMethod.GET)
public String loadDashboardPage (Model model) {

    /*Users signup*/
    model.addAttribute("user", new User());
    model.addAttribute("credentials", new Credentials());
    model.addAttribute("contacts", new Contacts());
    model.addAttribute("address", new Address());

    return "dashboard";
}

以下是我在eclipse控制台中遇到的错误:

java.lang.NullPointerException: null
at com.applicationSample.App.validator.userValidator.validate(UserValidator.java:46) ~[classes/:na]
at com.applicationSample.App.controller.SignupController.newUser(SignupController.java:144) ~[classes/:na]

您可以在这里找到验证程序类的代码:

@Override
public void validate(Object target, Errors errors) {

    User user = (User) target;
    String name = user.getName().trim();
    String surname = user.getSurname().trim();

    if (name.isEmpty()) {
        errors.rejectValue("name", "required");
    }

    if (surname.isEmpty()) {
        errors.rejectValue("surname", "required"); 
    }
}

我在html文件中使用thymeleaf绑定数据。另外,我已经在一个类似的方法中使用了这种方法,而且效果很好。我看不出错误在哪里,有什么帮助吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题