senzacionale
senzacionale

Reputation: 20906

code in constructor in java is called only once even page refreshed

is it possible in java that code in constructor is called only once even if page is refreshed via some actionListener. In C# Page.PostBack method works fine but here in java i can not find right method.

Upvotes: 0

Views: 1584

Answers (2)

Kerem Baydoğan
Kerem Baydoğan

Reputation: 10722

If you are talking about JSF then you need to change your BackingBeans scope from "Application" or "Session" to "Request".

This way your constructor works per request.

Example for JSF 2.0:

@ManagedBean()
@SessionScoped
public class MyBackingBean {
  ...
}

@ManagedBean()
@RequestScoped
public class MyBackingBean {
  ...
}

Upvotes: 3

pakore
pakore

Reputation: 11497

You can know when it's postback with a function such as:

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

@ManagedBean
public class HelperBean {

     public boolean isPostback() {
            FacesContext context = FacesContext.getCurrentInstance();
            return context.getRenderKit().getResponseStateManager().isPostback(context);
        }

}

If for every refresh the default constructor is called, that means that your bean is RequestScoped. A refresh (GET) or a postback (POST) are considered as requests, so the bean will be created for every request. There are other instantiation options such as SessionScoped or ApplicationScoped or just instantiate it when a postback occurs, with the above function.

Setting the scope a-la-JSF1.2

Edit your faces-config.xml file located under /WEB-INF:

 <managed-bean>
  <managed-bean-name>myBean</managed-bean-name>
  <managed-bean-class>com.mypackage.myBean</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
 </managed-bean>

you can use request, session or application

Upvotes: 4

Related Questions