JSF 2 - f:selectItems with a Date keyed Map

青春壹個敷衍的年華 提交于 2019-11-28 01:37:33

Using the date time converter should have been the right solution. Your "more cryptic validation error" turns out to be just this:

It was "form:location: Validation Error: Value is not valid

This will occur when the Object#equals() test of the selected item has not returned true for any of the available items. So, the selected Date did not match any of the available Date instances.

And indeed, the converter="javax.faces.DateTime" (aka <f:convertDateTime />) ignores by default the time part. It prints by default the "short" date style like "Dec 27, 2012" Rightclick page in browser, choose View Source to see it yourself.

<option value="Dec 27, 2012">DATEVALUE1</option>

When JSF converts the string submitted value in that format back to a concrete Date instance, it becomes basically 2012-12-27 00:00:00.000 while the dates provided in your map have apparently the time part still set, causing the equals() to always fail unless the map of available dates is by coincidence generated at exactly 00:00:00.000 midnight.

There are 2 solutions for this problem:

  1. Remove the time part of the dates in your mapping. You can use java.util.Calendar for this (or better, Joda Time).

  2. Use <f:convertDateTime pattern="yyyyMMddHHmmssSSS"/> instead to convert the entire date/time up to with the last milli second.

    <h:selectOneMenu value="#{dropDown.selectedDate}">
        <f:selectItems value="#{mapValues.dateMap.entrySet()}" var="entry" itemLabel="#{entry.value}" itemValue="#{entry.key}" />
        <f:convertDateTime pattern="yyyyMMddHHmmssSSS" />
    </h:selectOneMenu>
    

    This way the option value becomes

    <option value="20121227114627792">DATEVALUE1</option>
    

    Be careful with timezone issues when you've configured JSF to use platform specific timezone instead of GMT as <f:convertDateTime> timezone. You'd like to explicitly add timeZone="UTC" attribute to the converter then.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!