How to send a person to a 404 page if f:viewParam / converter returns null?

匆匆过客 提交于 2019-12-02 06:12:27

问题


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>

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?

EDIT:

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.

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.


回答1:


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

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

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.

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;


来源:https://stackoverflow.com/questions/15796497/how-to-send-a-person-to-a-404-page-if-fviewparam-converter-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!