Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model.addAttribute : Failed to convert value of type 'java.util.Arrays$ArrayList' to required type 'java.lang.String'

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.

like image 920
Stefan Fischer Avatar asked Nov 07 '22 19:11

Stefan Fischer


1 Answers

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.

like image 126
Ubercool Avatar answered Nov 14 '22 23:11

Ubercool