JSF calls methods when managed bean constructor sends 404 ERROR CODE

前端 未结 1 2034
遇见更好的自我
遇见更好的自我 2020-12-10 08:10

In a JSF managed bean constructor, I load a entity from database usint a request parameter. Some times, the entity is not in database and I want to show other JSF (.xhtml) p

相关标签:
1条回答
  • 2020-12-10 08:43

    You're basically trying to perform front controller logic while rendering the view. You should do it before rendering the view. Because, once you start rendering the view, it's already too late to change the view to a different destination, e.g. an error page as in your case. You namely cannot take the already sent response back from the client.

    In JSF 2.2 you can use <f:viewAction> for this.

    <f:metadata>
        <f:viewAction action="#{bean.init}" />
    </f:metadata>
    
    public void init() {
        // ...
    
        if (someCondition) {
            context.getExternalContext().responseSendError(404, "some message");
            context.responseComplete();
        }
    }
    

    (note that whenever you need to import javax.servlet.* classes into your JSF backing bean, you should absolutely stop and look if the functionality isn't already available in ExternalContext or otherwise think twice if you're doing things the right way, e.g. perhaps you needed a servlet filter; also note that you need to explicitly tell JSF that you've completed the response, otherwise it will still attempt to render the view)

    In JSF 2.0/2.1 you can use <f:event type="preRenderView"> for this. See also among others What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

    In case you're actually trying to validate a HTTP request parameter and you also happen to use OmniFaces, you may consider using <f:viewParam> with a true JSF validator and control the sendError with OmniFaces <o:viewParamValidationFailed>.

    0 讨论(0)
提交回复
热议问题