Reputation: 7836
I have a cache that I would like to invalidate whenever user issues a F5 request in the browser. I am running a JSF 2.0 application. Is there a way to do this?
Upvotes: 3
Views: 5956
Reputation: 763
I found a solution that i have implemented on beyondjava
<f:metadata>
<f:viewAction action="#{f5Detector.checkF5}" onPostBack="true"/>
</f:metadata>
Java class (just changed ManagedBean to Named)
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.inject.Named;
@SessionScoped
@Named
public class F5Detector {
private String previousPage = null;
public void checkF5() {
String msg = "";
UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
String id = viewRoot.getViewId();
if (previousPage != null && (previousPage.equals(id))) {
// It's a reload event
}
previousPage = id;
}
}
Upvotes: 0
Reputation: 19
I think this will be helpful you can detect any key press with key code.
Refer this link for key codes. https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/ui/Keyboard.html
<rich:hotKey key="f5" onkeydown="if (event.keyCode == 116) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+R" onkeydown="if (event.keyCode == 123) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+f5" onkeydown="if (event.keyCode == 154) return false;" handler="return false;" disableInInput="true" />
Upvotes: 1
Reputation: 3160
I've uploaded a running F5 detector project on the BootsFaces demo collection on GitHub and written a short blog post. Basically, the the answer of Kolossus is correct. The ViewAction is also triggered on the first page load, so I added a couple of lines to detect that, too.
Upvotes: 0
Reputation: 20691
Use the FacesContext.getCurrentInstance().isPostBack()
to check whether a page request is a reload of the same page. An ideal spot for this would be in a <f:viewAction/>
( new with JSF-2.2) or preRenderView
event.
Define the backing bean method
public static boolean isPostback() {
return FacesContext.getCurrentInstance().isPostback();
}
Use either
<f:metadata>
<f:viewAction action="#{bean.isPostBack}" onPostBack="true"/>
</f:metadata>
f:event
<f:metadata>
<f:event type="preRenderView" listener="#{bean.isPostBack}"/>
</f:metadata>
OR
You could skip the whole backing bean isPostBack
check altogether and directly execute the cache-clearing method directly from the page.
<f:metadata>
<f:viewAction action="#{bean.clearCache}" rendered="#{facesContext.postBack}" onPostBack="true"/>
</f:metadata>
f:event
<f:metadata>
<f:event type="preRenderView" rendered="#{facesContext.postBack}" listener="#{bean.clearCache}"/>
</f:metadata>
The benefit with this approach is that you write less code, and your cache clearing mechanism still executes only when the request is a post back
Upvotes: 3