Nikrango
Nikrango

Reputation: 97

How to use a List as a Model Attribute in Spring?

I have my Home controller like this:

    @RequestMapping("/")
    public ModelAndView welcome(@ModelAttribute("myValuesInRows") List<String> myValuesInRows,  ModelMap model) {
        List<Spravochnik> dropDown = spravochnikService.findAll("sprav_of_spravs");
        List<String> justValuesInRows = new ArrayList<>();
        for(Spravochnik sprav : dropDown) {
            for(List<String> vals : sprav.getValuesInRows()) {
                for(String v : vals) {
                    justValuesInRows.add(v);
                }
            }
        }
        for(int i=1; i<justValuesInRows.size(); i+=2) {
            myValuesInRows.add(justValuesInRows.get(i));
        }
        model.addAttribute("myValuesInRows", myValuesInRows);
        return new ModelAndView("home", model);
    }

and my Home view has this Select I'm using:

<f:form>
<f:select path="myValuesInRows" items="${myValuesInRows}" name="tableName" id="tableName">
</f:select>
</f:form>

When I try to show it Spring shows this error:

No primary or default constructor found for interface java.util.List.

I would like to connect my select to this List I'm passing, how is it done here?

Upvotes: 2

Views: 10414

Answers (1)

lealceldeiro
lealceldeiro

Reputation: 14958

Use one of the classes which implement List, such as ArrayList or LinkedList, which have default constructors.

@ModelAttribute("myValuesInRows") ArrayList<String> myValuesInRows

You can find a list of all known implementing classes of List here:

https://docs.oracle.com/javase/8/docs/api/java/util/List.html

Upvotes: 3

Related Questions