Ad

Model.addAttribute : Failed To Convert Value Of Type 'java.util.Arrays$ArrayList' To Required Type 'java.lang.String'

- 1 answer

I want to add a list of items to a Spring Model. It sometimes throws ConversionFailedException. The method in question:

private void addAuthoritiesToModel(Model model){
    List<Authority> allAuthorities = Arrays.asList(
            Authority.of("ROLE_ADMIN","Admin"),
            Authority.of("ROLE_USER","User")
    );

    model.addAttribute("allAuthorities",allAuthorities);
}

The method throws on the last line. The curious thing it only does so, when called from a particular method and not others. For example, it works fine here:

@GetMapping("/users/new")
public String newUserForm(Model model){
    model.addAttribute("user",User.blank());
    model.addAttribute("newUser",true);
    addAuthoritiesToModel(model);

    return "user_details";
}

But it blows here:

@PostMapping(value = {"/users","/profile","/users/{any}"})
public String postUser(@Valid @ModelAttribute("user") User user,
                       BindingResult bindingResult,
                       @RequestParam("newPassword") Optional<String> newPassword,
                       @RequestParam("confirmPassword") Optional<String> confirmPassword,
                       RedirectAttributes redirectAttributes,
                       @PathVariable("any") String pathVariable
                      ){

    if(bindingResult.hasErrors()) {
        if(user.getId()==null)
            redirectAttributes.addAttribute("newUser",true);
        addAuthoritiesToModel(redirectAttributes);
        return "user_details";
    }

...
}

I have tried exchanging Arrays.asList to another List implementation, but that doesn't solve the problem. And it wouldn't explain, why it doesn't work in the first case.

Ad

Answer

There is difference between Model and RedirectAttributes. The values in RedirectAttributes are getting formatted as String.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html

A specialization of the Model interface that controllers can use to select attributes for a redirect scenario. Since the intent of adding redirect attributes is very explicit -- i.e. to be used for a redirect URL, attribute values may be formatted as Strings and stored that way to make them eligible to be appended to the query string or expanded as URI variables in org.springframework.web.servlet.view.RedirectView.

You should not use unless required for redirecting and in such case should be string values.

Ad
source: stackoverflow.com
Ad