简体   繁体   中英

Reset JSF Backing Bean(View or Session Scope)

I want to reset by JSF backing bean when some method is invoked. Assume that there is a command button, someone press it and after succesfull transaction, my View or Session scope JSF bean should be reseted. Is there a way to do that?

Thank

A view scoped bean will be recreated when you return non- null or non- void from the action method, even if it would go back to the same view. So, just return a String from the action method, even if it's just an empty string:

public String submit() {
    // ...

    return "";
}

To make it complete, you could consider sending a redirect by appending the ?faces-redirect=true query string to the returned outcome.

public String submit() {
    // ...

    return "viewId?faces-redirect=true";
}

A session scoped bean is in first place the wrong scope for whatever you're currently trying to achieve. The bean in question should have been be a view scoped one. Ignoring that, you could just recreate the model in the action method, or very maybe invalidate the session altogether (which would only also destroy all other view and session scoped beans, not sure if that is what you're after though).

I found the solution for View scope.

    public static void removeViewScopedBean(String beanName) 
    {
      FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(beanName);
    }

just clear all views:

FacesContext.getCurrentInstance().getViewRoot().getViewMap().clear();

and remember to implements Serializable in all views

您还可以从javascript刷新页面,因此ViewScoped Bean将被重置,例如在primefaces commandButton中:

<p:commandButton value="Button" action="#{bean.someAction()}" oncomplete="location.reload()"/>

I solve the problem with code like this:

((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getSession().removeAttribute("bean name");            

By this way I enter to session scoped bean and reset it without the data that was there before

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM