JSF 2 - f:selectItems with a Date keyed Map

前端 未结 1 551
感动是毒
感动是毒 2020-12-06 23:26

The below selectItems is fed from a Session Scoped Map. When the user clicks the Submit button, it is supposed to set a date field in the Request Scoped backing bean and dis

相关标签:
1条回答
  • 2020-12-06 23:36

    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.

    0 讨论(0)
提交回复
热议问题