@NotNull Bean验证被viewParam忽略 [英] @NotNull Bean Validation ignored for viewParam
问题描述
问题
我正在尝试验证强制性的GET请求参数.
I'm trying to validate a mandatory GET request parameter.
在视图中,我添加了一个对应的viewParam标签.
In the view I've added a corresponding viewParam tag.
<f:metadata>
<f:viewParam name="customerId" value="#{customerDetailBean.customerId}"/>
</f:metadata>
我的CDI bean看起来像这样
And my CDI bean looks like this
@Model
public class CustomerDetailBean {
@NotNull
private Integer customerId;
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
}
当我使用以下请求时,验证工作正常,并显示预期的验证消息.
When I use the following request, validation works fine and the expected validation message is displayed.
http://localhost:8080/getsupport/customerdetail.jsf?customerId=
但是,当我通过删除参数customerId更改请求时,将跳过验证并且不显示任何消息.
However, when I change the request by removing the parameter customerId, validation is skipped and no message is shown.
http://localhost:8080/getsupport/customerdetail.jsf
有没有办法使它按预期工作?
Is there a way to make it work as expected?
解决方法
我已将viewParam声明更改为
I've changed my viewParam declaration to
<f:metadata>
<f:viewParam name="customerId" value="#{customerDetailBean.customerId}" required="true" />
</f:metadata>
该更新的版本可以与第二个请求一起正常工作.无论如何,我还是希望使用bean验证.
That updated version works fine with the second request. Anyway I would prefer to use bean validation.
我的设置
- Mojarra JSF 2.2.7
- 焊接2.2.1.决赛
- 休眠验证器5.1.1.最终版
- Tomcat 7.0.54
web.xml
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
推荐答案
不幸的是,这是按设计方式工作".未提交任何内容时,将跳过所有验证.仅<f:viewParam required>
有特殊处理.当什么都没有提交时,也会考虑它.另请参见UIViewParameter#processValidators()
源代码.
This is, unfortunately, "working as designed". All validation is skipped when nothing's been submitted. Only the <f:viewParam required>
has special treatment. It's also considered when nothing's been submitted. See also UIViewParameter#processValidators()
javadoc and source code.
在 Mojarra问题跟踪器中,我只能找到问题3339 .
In the Mojarra issue tracker I can only find issue 3058 as a related issue, whereby the <f:validateRequired>
isn't being considered. This is technically actually exactly the same problem as you're facing with @NotNull
. I've created issue 3339 on this.
与此同时,您最好的选择是退回required="true"
.自定义组件也可以,但是据我所知这并不是一件容易的事.
In the meanwhile, your best bet is falling back to required="true"
. A custom component can also, but as far as I see this isn't going to be trivial.
更新:毕竟,此修复相对容易,并且 OmniFaces
Update: after all, the fix is relatively easy and has been implemented in OmniFaces <o:viewParam>
in the current 2.0 snapshot release.
这篇关于@NotNull Bean验证被viewParam忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!