Refresh JSF page programmatically from JavaBean

When business logic in JavaBean decides that forced jsf page refresh is needed, it can be done from logic’s level. Add this code to your logic (prefereably put it in some refresh() method):

FacesContext context = FacesContext.getCurrentInstance();
String viewId = context.getViewRoot().getViewId();
ViewHandler handler = context.getApplication().getViewHandler();
UIViewRoot root = handler.createView(context, viewId);
root.setViewId(viewId);
context.setViewRoot(root);

Browsers may have cache enabled, so some cached elements may not be refreshed. If this is your case, you should also add header to Http response, that will force browser not to use cache:

response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);

Cached elements were not my problem, so the second snippet is not tested by me. For more info, please see following sources: OTN Discussion Forum, Refresh current JSF page and caching on StackOverflow.

Note: page refresh done that way means sending Http Response – one Http Request can have only one Http Response. You can’t use this code if you have already sent your response earlier for this particular Http Request.

For example – while performing file download. The file download data is sent in Http Response, so unfortunately there is no way to refresh page programmaticaly. Probably Ajax refresh could help you, if just some of the components should be rerendered. This problem is described in threads: StackOverflow thread 1Coderanch question, another Coderanch problem, refresh after response is commited, and the last one Coderanch – so.. just impossible…

 

.. so maybe better to use this JavaScript delayed reload – give it a try!

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

8 thoughts on “Refresh JSF page programmatically from JavaBean

  1. Hi….Page refresh after a file download is not imposible. I had the same problem and I solved this way:

    ….
    response.setContentType(“application/pdf”);
    response.setHeader(“Content-Disposition”, “attachment; filename=” + getFileName());
    response.setHeader(“Refresh”, “3; url = pageToRefresh.jsf”);
    ServletOutputStream stream = response.getOutputStream();
    …..

    The “Refresh” header can be used to reload the desired page after the file download. It can be the same page from which the file was downloaded.

  2. Hi Claudia, it works only when you downlod the file. however, if you press cancel button the page is not refreshed. Any solution for that ?

Give Your feedback: