h:inputFile 其他输入提交或验证失败后值变为空白,如何保留其值?

h:inputFile value becomes blank after submit or validation fail of other input, how to retain its value?

对于许多其他标准 JSF 组件,当提交表单并且服务器端验证失败时,页面将再次呈现,并填充先前提交的表单字段,以供用户编辑和重新提交。我正在寻找新 h:inputFile 的相同行为,但我没有找到它。

作为一个简单的例子,我有一个带有 h:inputText 和 h:inputFile 的表单。 inputText 启用了服务器端验证。如果用户输入无效文本和 select 文件并提交,则上传文件并呈现表单,其中文本字段中的无效文本和指示验证结果的 h:message。我要解决的问题是此时他们更正了文本输入,但必须再次 select 一个文件,然后再次上传。我缺少一些基本的东西,还是这是预期的行为?

HTML 不允许预填充 <input type="file">,否则会打开 huge security hole。由于 JSF 在这种情况下只是一个 HTML 代码生成器,因此它对此无能为力。

你最好的选择是 ajax- 提交表单并 ajax- 呈现 真正需要更新的部分,例如消息(即不要使用 render="@form")。这样初始输入值就保留了。

例如

<h:form enctype="multipart/form-data">
    <h:inputText id="text" />
    <h:message id="m_text" for="text" />

    <h:inputFile id="file" />
    <h:message id="m_file" for="file" />

    <h:commandButton value="submit">
        <f:ajax execute="@form" render="m_text m_file" />
    </h:commandButton>
</h:form>

另请参阅:

  • Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes