JSF 2: Using enums in the rendered attribute

后端 未结 4 1300
忘掉有多难
忘掉有多难 2020-12-24 08:22

Is there any way to check declaratively whether an enum has a specified value. For example:



        
4条回答
  •  误落风尘
    2020-12-24 08:32

    I solved a similar problem by statically dumping all the enum keys (which are used in the rendered UI components) in a map and then I use a static getByKey method to convert the value from the UI into an actual native enum in the setter, throwing an Exception if the value provided is invalid:

    public enum ReportType {
    
        FILING("F", "Filings"),
        RESOLUTION("R", "Resolutions"),
        BASIS("B", "Bases"),
        STAFF("T", "Staff Counts"),
        COUNTS("I", "Counts");
    
        private String key;
        private String label;
    
        private static Map keyMap = new HashMap();  
    
        static {
            for(ReportType type : ReportType.values()) {
                keyMap.put(type.getKey(), type);
            }
        }
    
        private ReportType(String _key, String _label) {
            this.key = _key;
            this.label = _label;
    
        }
    
        public String getKey() {
            return this.key;
        }
    
        public String getLabel() {
            return this.label;
        }
    
        public static List getValueList() {
            return Arrays.asList(ReportType.values());
        }
    
        public static ReportType getByKey(String _key) {
            ReportType result = keyMap.get(_key);
    
            if(result == null) {
                throw new IllegalArgumentException("Invalid report type key: " + _key);
            }
    
            return result;
        }
    }
    

    In the UI tier, the enum key is used as the value and the enum label is used as the label:

    
    

    In the managed bean, I convert the enum into a renderable list, using the getValueList() from the enum:

    public List getAllReportTypes() {
        return ReportType.getValueList();
    }
    

    Finally, the [g|s]etters in the managed bean look as follows:

    public String getReportType() {
        return this.crtRptType.getKey();
    }
    
    public void setReportType(String _val) {
        this.crtRptType = ReportType.getByKey(_val);
    }
    

提交回复
热议问题