作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
单击按钮时如何使用 JSF 跳过 JSR-303 Bean 验证?
一个有点冗长的问题来解释一些方法......考虑一个表单中的列表:
<h:form id="form">
<h:commandButton value="Add row">
<f:ajax execute="foo" listener="#{bean.add()}" render="foo" />
</h:commandButton>
<h:dataTable id="foo" var="foo" value="#{bean.foos}">
<h:column>
Name: <h:inputText id="field" value="#{foo.name}" required="true" />
<h:messages for="field" />
</h:column>
<h:column>
<h:commandButton value="Remove">
<f:ajax execute=":form:foo" listener="#{bean.remove(foo)}" render=":form:foo" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
当用户单击添加或删除行时,该操作应在不进行验证的情况下执行。问题是,JSF 重新呈现整个列表并尝试验证它。如果存在未验证的草稿更改,则会发生验证错误,并且永远不会调用监听器方法(因为失败的验证会阻止这种情况)。但是,将 immediate="true"
添加到 f:ajax 中允许方法在出现验证错误的情况下执行。但是,验证错误仍然会发生并显示在此处。
我看到两个选项:
1) 使用immediate="true"并且不显示验证错误
对于非验证按钮,设置immediate="true",对于 h:messages 设置:
<h:messages rendered="#{param['SHOW_VALIDATION']}" />
然后设置保存按钮(实际上应该尝试保存表单)来发送该参数:
<h:commandButton>
<f:param name="SHOW_VALIDATION" value="true" />
</h:commandButton>
这会导致验证发生,但除非存在 SHOW_VALIDATION
参数,否则不会显示消息。
2) 有条件地在 Facelet 中声明验证:
<h:inputText>
<f:validateRequired disabled="#{!param['VALIDATE']}" />
</h:inputText>
和保存按钮:
<h:commandButton>
<f:param name="VALIDATE" value="true" />
</h:commandButton>
这会导致字段仅在存在 VALIDATE
参数时(=按下“保存”按钮时)才验证。
但这些看起来有点像黑客。如何简单地使用 JSR-303 Bean 验证但在声明时跳过它?
最佳答案
将事件处理程序设置为 immediate=true
并在退出之前调用 FacesContext.renderResponse()
。
更新:
示例表单中的修改:
<h:form id="form">
<h:commandButton value="Add row">
<!-- Added immediate="true" to call bean.add() before validation phase -->
<f:ajax execute="foo" listener="#{bean.add()}" render="foo" immediate="true"/>
</h:commandButton>
<h:dataTable id="foo" var="foo" value="#{bean.foos}">
<h:column>
Name: <h:inputText id="field" value="#{foo.name}" required="true" />
<h:messages for="field" />
</h:column>
<h:column>
<h:commandButton value="Remove">
<!-- Added immediate="true" to call bean.remove() before validation phase -->
<f:ajax execute=":form:foo" listener="#{bean.remove(foo)}" render=":form:foo" immediate="true"/>
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
对 bean 代码的修改:
...
public void add() {
// Your add() code
...
// Added FacesContext.renderResponse() call to skip to render response phase
FacesContext.getCurrentInstance().renderResponse();
}
...
public void remove() {
// Your remove() code
...
// Added FacesContext.renderResponse() call to skip to render response phase
FacesContext.getCurrentInstance().renderResponse();
}
...
关于JSF 2.0 : How to skip JSR-303 bean validation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4852496/
我是一名优秀的程序员,十分优秀!