Exception thrown in @PostConstruct causes IllegalStateException in JSF 2.1

半腔热情 提交于 2020-01-15 11:26:11

问题


I have an init method on my @ViewScoped mananged bean. In the post construct i load data from the db. I have a custom ExceptionHandlerWrapper to catch all excptions and send to an error pages. However when @PostConstuct throws an exception i recieve an IllegalStateException and am not redirected to the error page. I have tried many combinations.....

Ive tried this inside my ExcpetionHandler

externalContext.getRequestMap().put(ERROR_BEAN_ID, ERROR_TEXT);
externalContext.dispatch(ERROR_PAGE);
fc.responseComplete();

This line below is what i originally had. It also doent work

externalContext.getFlash().put(ERROR_BEAN_ID, ERROR_TEXT);
nav.handleNavigation(fc, null, ERROR_PAGE);
fc.renderResponse();

These all cause IllegalStateExceptions. I also called redirect with the same result.

Can you globally catch errors thrown from @PostConstruct?


回答1:


These all cause IllegalStateExceptions.

With the message "Response already committed", I assume? Well, that's a point of no return. A part of the response has already been sent to the client (the webbrowser). It's not possible to take the already sent bytes back. The server will end up with this exception in the logs and the client will end up with a halfbaked response.

What can you do?

Most straightforward way would be to enlarge the response buffer size to the size of the largest page. For example, 64KB:

<context-param>
    <param-name>javax.faces.FACELETS_BUFFER_SIZE</param-name>
    <param-value>65536</param-value>
</context-param>

It defaults to ~2KB depending on the server configuration. You only need to keep in mind that this may be memory hogging when your server has to process relatively a lot of requests/responses. Profile and measure properly.

Another way is to reference the bean before the response is to be rendered/committed so that it's (post)construction is triggered before that point. Perhaps the bean in question is referenced for the first time at the very bottom of the view, long beyond the ~2KB response size border. You could take over the job of @PostConstruct with a <f:event type="preRenderView"> somewhere in the top of the view. E.g.

<f:event type="preRenderView" listener="#{bean.init}" />

with

public void init() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // Do here your original @PostConstruct job.
    }
}


来源:https://stackoverflow.com/questions/9845163/exception-thrown-in-postconstruct-causes-illegalstateexception-in-jsf-2-1

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