How to save an array in JSF with ui:repeat + h:inputText + managed bean?

前端 未结 2 948
旧时难觅i
旧时难觅i 2021-02-04 22:56

In a postgres database I have a table with, among others, an int[] field.

In my model I have a persisted bean that maps the table, including the int[] field. In this cla

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 23:13

    If editableBaseSetList is an int[], then baseNumber is an int. You're now binding the input text component to this int.

    This binding is however not bidirectional. The input element only gets to see the element you are binding to it, not the collection from which it originates. It thus has no knowledge of how to update this collection.

    You thus need to bind to something that can be updated. If your list for instance contained an IntHolder with a getter and setter for the internal integer (say getInt() and setInt()), and the list would be ArrayList you would use:

    
        
    
    

    After the postback, JSF will call the setInt() method on each IntHolder in the list with the supplied values.

    For a collection that already holds integers or other immutable types, it can be a bit of a hassle to convert it to such collection mentioned above. There is however also another solution. There you don't use the var attribute of ui:repeat but use its index. You then give the h:inputText a binding to the collection indexed by this index var.

    E.g.

    Suppose you have the following bean:

    import javax.annotation.PostConstruct;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.ViewScoped;
    
    @ManagedBean
    @ViewScoped
    public class RepeatBean {
    
        List list;
    
        public List getList() {
            return list;
        }
    
        @PostConstruct
        public void initList() {
            list = new ArrayList();
            list.add(10);
            list.add(20);
            list.add(30);
        }
    
        public String save() {
            // list now contains the values provided by the user.
            return "";
    
        }
    
    }
    

    Used on the following Facelet:

    
    
        
    
            
                            
                    
                
                
            
    
        
    
    

    This will initially display 10 20 30 on your screen. When you change the numbers and click save, you can verify via e.g. a break-point that the list instance variable contains the updated numbers.

提交回复
热议问题