在o:viewParamValidationFailed中区分转换失败和验证失败 [英] Distinguish between conversion failure and validation failure in o:viewParamValidationFailed

查看:71
本文介绍了在o:viewParamValidationFailed中区分转换失败和验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在当前项目中使用 OmniFaces <o:viewParam>标记处理程序.我喜欢,很棒.甚至更大的是 <o:viewParamValidationFailed> .现在,如果验证或转换失败,我们可以发送错误.但我想知道,是否有可能区分转换失败和验证失败.

I am using the OmniFaces <o:viewParam> taghandler in my current project. I like it, it's great. And even greater is the <o:viewParamValidationFailed>. Now, we are able to send an error if validation or conversion fails. But I wonder, whether it is possible to distinguish between conversion failure and validation failure.

假设我们要发送 Bad Request ,如果给定的视图参数格式错误且无法转换;为此,如果转换成功,则发送未找到,但是在数据库中找不到该对象;并在用户不应访问成功获取的对象后发送禁止.

Let's say we want to send a Bad Request if the given view param in malformed and can not be converted; for that matter send a Not Found if conversion succeeded, but the object could not be found in the database; and send a Forbidden if the successfully fetched object should not be accessed by the user.

有人知道实现这一目标的方法吗?

Does anybody know a way to achieve this?

推荐答案

不幸的是,当您只有UIInput#isValid()时,无法区分ConverterExceptionValidatorException.从理论上讲,您可以检查并测试人脸消息,看它是否表示转换或验证错误,但这不是一种可靠的方法,当然,在本地化时也不是这样.

It's unfortunately not possible to distinguish between a ConverterException and ValidatorException when you've only UIInput#isValid() at hands. Theoretically, you could check and test the faces message to see if it represents a conversion or validation error, but this is not a robust approach, certainly not when it's localized.

另一方面,可以在同一参数名称上声明多个视图参数.您不必指定value即可将其设置为模型值.

On the other hand, it's possible to declare multiple view parameters on the same parameter name. You do not necessarily need to specify a value to set it as model value.

这是一个基于您的描述的示例,请注意,模型值仅在最后一个值上设置:

Here's an example based on your description, note that the model value is only set on the last one:

<o:viewParam name="foo">
    <f:converter converterId="yourFooConverter" />
    <o:viewParamValidationFailed sendError="400" />
</o:viewParam>
<o:viewParam name="foo">
    <f:converter converterId="yourFooConverter" />
    <f:validateRequired />
    <o:viewParamValidationFailed sendError="404" />
</o:viewParam>
<o:viewParam name="foo" value="#{bean.foo}">
    <f:converter converterId="yourFooConverter" />
    <f:validateRequired />
    <f:validator validatorId="yourRestrictedAccessValidator" />
    <o:viewParamValidationFailed sendError="403" />
</o:viewParam>

为了避免每次转换都调用DB的昂贵工作,让YourFooConverter实现将转换后的值存储为FacesContext的自定义属性,然后在每次通过时对其进行检查.

To avoid the expensive job of calling the DB on every conversion, let the YourFooConverter implementation store the converted value as a custom attribute of the FacesContext and then check it on every pass.

这篇关于在o:viewParamValidationFailed中区分转换失败和验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆