如果f:viewParam/转换器返回null,如何将人发送到404页面? [英] How to send a person to a 404 page if f:viewParam / converter returns null?

查看:97
本文介绍了如果f:viewParam/转换器返回null,如何将人发送到404页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个带有视图参数的页面,例如/widgets?widgetId=1

Lets say you had a page with a view param, like /widgets?widgetId=1

    <f:metadata>
        <f:viewParam
            name="widgetId"
            value="#{widgetIdMB.widgetId}"
            converter="#{widgetIDConverter}" />
    </f:metadata>

因此,更不用说您的转换器抛出ConverterException了,因为有人试图导航到数据库中不存在的/widgets?widgetId=1000000.发生这种情况时,是否可以将其发送到404页面?

So, less say your converter throws a ConverterException, because someone tried to navigate to /widgets?widgetId=1000000, which doesn't exist in the database. Is there a way to send the person to the 404 page when that happens?

我使用转换器来转换值.如果无法在数据库中查找该值,则转换器将返回null,而不是引发ConverterException.

I used a converter to convert the value. If the value can't be looked up in the database, the converter returns null, rather than throwing a ConverterException.

然后我使用验证器.验证器将抛出validationexception,但不会在调用omnifaces实用程序类之后发出:Faces.responseSendError(404, "Not Found");

Then I use a validator. The validator will throw a validationexception, but not after calling the omnifaces utility class: Faces.responseSendError(404, "Not Found");

这似乎是关注点分离的最佳实现.

This seems like the best implementation of separation of concerns.

推荐答案

使用

Use ExternalContext#responseSendError() in the Converter when the condition is met.

context.getExternalContext().responseSendError(404, message);
context.responseComplete();
return null;

别忘了之后再调用FacesContext#responseComplete(),这与ExternalContext#redirect()相反,由于某些原因并没有隐式完成.否则,JSF会将当前页面附加到响应末尾,或者在已经提交后抛出IllegalStateException.

Don't forget to call FacesContext#responseComplete() afterwards, this isn't implicitly been done for some reason, in contrary to ExternalContext#redirect(). Otherwise JSF will append the current page to end of response, or throw an IllegalStateException when it's already committed.

除了魔术数字404,您还可以使用 HttpServletResponse.SC_NOT_FOUND .

Instead of the magic number 404 you can also use HttpServletResponse.SC_NOT_FOUND.

context.getExternalContext().responseSendError(HttpServletResponse.SC_NOT_FOUND, message);
context.responseComplete();
return null;

这篇关于如果f:viewParam/转换器返回null,如何将人发送到404页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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