It look's like your Managed Bean is @SessionScoped
and the constructor will be called only the first time the user access to a page when the bean is used.
In JSF 2, this can be achieved changing the Managed Bean to @ViewScoped
.
@ManagedBean
@ViewScoped
public class Bean {
public Bean() {
}
@PostConstruct
public void init() {
clearMsg();
}
}
BalusC gives a good explanation about JSF Managed Bean scopes in this answer: How to choose the right bean scope?. Also, I recommend you to read the link at the bottom of the answer to have a better understanding of these concepts.
In JSF 1.x, you should configure the Managed Bean to request scope in the faces-config.xml
file and call the clearMsg
in the @PostConstruct public void init
method. Note that this means that the clearMsg
method will be invoked on every request that involves creating the managed bean class (even ajax requests). In order to solve the problem, you should provide more info about how and when you call this bean in your JSF code. By default, you can solve this by setting a flag in the session and check against this flag before calling the clearMsg
method (or the methods you only need to call once).
public class Bean {
public Bean() {
}
@PostConstruct
public void init() {
HttpSession session = ((HttpRequest)FacesContext.getCurrentInstance().
getExternalContext().getRequest()).getSession();
if (session.getAttribute("flag") == null) {
clearMsg();
//other methods...
}
}
}
Faces configuration
<managed-bean>
<managed-bean-name>bean</managed-bean-name>
<managed-bean-class>your.package.Bean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
There's a way to simulate the request scope Managed Bean into a @ViewScoped
by using @KeepAlive
annotation from RichFaces 3
. Take into account that the bean will be alive until you change the view by making an explicit redirect. Based on this, the code would be like this:
@KeepAlive
public class Bean {
public Bean() {
}
@PostConstruct
public void init() {
//no need to use session flags
clearMsg();
//other methods...
}
}