问题
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