Detect F5 or reload and always send it home. JSF

2

I need to know if there is any way to identify when a user reloads the page using f5 or update the browser button to schedule an action and that it always redirects to the homepage.

I am using a phase listener where I can compare before loading each page the id of the view and compare them if they are the same I do a re address to the navigation rule of the home.

The problem with this method is that they do not differ when I update, when the page is reloaded with Ajax , for example in the pager of a table.

Is there any option in which I can identify if the recharge comes from ajax or if it comes from f5 or browser update button?

This is the code of the listener . Thanks

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

@SuppressWarnings("serial")
public class PostRedirectGetListener implements PhaseListener {
private String previousPage = null;

public PhaseId getPhaseId() {

    return PhaseId.RENDER_RESPONSE;
}

public void beforePhase(PhaseEvent event) {

    String msg = "";
    UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
    String id = viewRoot.getViewId();       
    if (previousPage == null) {
        msg = "First page ever";
    } else if (previousPage.equals(id)) {
        msg = "F5 or reload";
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = "urlHome";
        facesContext.getApplication().getNavigationHandler()
                .handleNavigation(facesContext, null, outcome);
    } else if (FacesContext.getCurrentInstance().isPostback()) {
        msg = "It's a postback";
    } else
        msg = "It's a navigation";
    previousPage = id;
    System.out.println(msg);
}


public void afterPhase(PhaseEvent event) {

}

}
    
asked by Oscar 24.06.2016 в 15:28
source

1 answer

2

In your view you can add the following:

<f:metadata>
   <f:viewAction action="#{f5Detector.checkF5}" onPostBack="true"/>
</f:metadata>

BackEnd

@SessionScoped
@ManagedBean
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;
  }
}

You can also do it using javascript, since pressing F5 activates the event window.onunload() event.

You can even try with.

<meta http-equiv="refresh" content="30; ,URL=http://redirecciona a ...">
    
answered by 24.06.2016 в 17:30