How to write a custom converter for

后端 未结 6 549
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:59

How can I write a custom converter when working with PrimeFaces components that use a list of POJO? My particular problem is with

<         


        
6条回答
  •  醉酒成梦
    2020-11-29 01:56

    Yes, you can write a converter that serializes/deserializes the objects in the picklist like this:

    @FacesConverter(value="PositionMetricConverter")
    public class PositionMetricConverter implements Converter {
    
        private static final Logger log = Logger.getLogger(PositionMetricConverter.class.getName());
    
        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
            try {
                byte[] data = Base64.decodeBase64(value);
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
                Object o = ois.readObject();
                ois.close();
                return o;
            } catch (Exception e) {
                log.log(Level.SEVERE, "Unable to decode PositionMetric!", e);
                return null;
            }
        }
    
        @Override
        public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(value);
                oos.close();
    
                return Base64.encodeBase64String(baos.toByteArray());
            } catch (IOException e) {
                log.log(Level.SEVERE, "Unable to encode PositionMetric!", e);
                return "";
            }
        }
    
    }
    

    Then apply this converter on your picklist like this:

    
    

    and make sure your objects are serializable.

提交回复
热议问题