Pages

Showing posts with label JSF. Show all posts
Showing posts with label JSF. Show all posts

Thursday, February 27, 2014

Why use @PostConstruct ?

http://docs.oracle.com/javaee/5/api/javax/annotation/PostConstruct.html
http://stackoverflow.com/questions/3406555/why-use-postconstruct

@PostConstruct (or post-construct, if declared in deployment descriptors) was introduced in Java EE 5 to all component types, including all web components (Servlet 2.5).


- The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection. The method annotated with PostConstruct MUST be invoked even if the class does not request any resources to be injected.Only one method can be annotated with this annotation.

*** The method on which the PostConstruct annotation is applied MUST fulfill all of the following criteria 

- The method MUST NOT have any parameters except in the case of EJB interceptors in which case it takes an InvocationC ontext object as defined by the EJB specification. 
- The return type of the method MUST be void.
- The method MUST NOT throw a checked exception.
- The method on which PostConstruct is applied MAY be public, protected, package private or private
- The method MUST NOT be static except for the application client
- The method MAY be final. - If the method throws an unchecked exception the class MUST NOT be put into service except in the case of EJBs where the EJB can handle exceptions and even recover from them.

Why use @PostConstruct ?

  • because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.
  • because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.

in JSF context : use @PostConstruct for @ManagedBean

http://stackoverflow.com/questions/15773350/initialization-of-list-in-a-jsf-managed-bean?lq=1
    There are implications regarding the scope of the managed bean
  1. @RequestScoped: In a managed bean with this annotation, the method will be called per submit of the JSF view concerned. A @RequestScoped bean is destroyed and recreated with every request, The implication of this is that depending on your setup, the list initialized in the @PostConstructmay be reset to empty or default values during each request. Under certain circumstances, conversion errors may occur as a result of the re-initialization of the list mid-JSF request.
  2. @ViewScoped: In a managed bean with this annotation, you're guaranteed to have the @PostConstruct method run once, if and only if you're dealing with the same instance of the @ViewScoped bean. If the viewscoped bean is destroyed and recreated, the @PostConstructmethod will run again.
  3. @SessionScoped: A bean with this annotation is created once and stays alive until the user's HTTP session ends. In this scenario, the @PostConstruct method is guaranteed to run once and only once until the bean is destroyed

Servlet init method vs PostConstruct method

http://javahowto.blogspot.com/2011/07/servlet-init-method-vs-postconstruct.html
invocation order and relationship of the two methods:
servlet class constructor --> PostConstruct --> init and init(ServletConfig)
So inside PostConstruct method at the second step, ServletConfig has not been initialized, and neither is ServletContext. CallinggetServletConfig() in PostConstruct returns null. Calling getServletContext() results in IllegalStateException in most servers (GlassFish 3, Tomcat 7 and JBoss 6), but returns null in Resin 4.
eg :
public class DpartmentBean {
    // service and resource inject
    @EJB
    HrSessionFacadeLocal hrService;
    // ui comp
    private RichTable departmentTable;
    public DpartmentBean() {
        this.departmentTable = new RichTable();
    }
             /**
                load data for table  when hrService injected
            */
    @PostConstruct
    public void initDepartmentTable() {
        if (hrService != null) {
            try {
                List<Departments> departments = hrService.getDepartmentsFindAll();
                this.departmentTable.setValue(departments);
            } catch (Exception e) {
                // TODO: Add catch code
                e.printStackTrace();
            }
        }
    }
}

Friday, January 24, 2014

Passing values from Page to Bean in JSF

refer to :
http://gik.firetrot.com/index.php/2013/07/19/passing-values-from-page-to-bean-in-jsf/


There are three ways to pass values from page to JSF ManagedBean:
  1. Passing value with f:param tag – using action attribute
  2. Passing value with f:attribute tag – using actionListener attribute
  3. Passing value with f:setPropertyActionListener tag – no need for additional dealing, value allplies directly to bean property!
example : 
case 1:
<p:commandButton value="Pass Param" action="#{PassParamBean.passParam}">
        <f:param name="someParamHolder" value="THIS is VALUE_OF_PARAM !!!" />    </p:commandButton>

case 2:
<p:commandButton value="Pass Attribute" actionListener="#{PassParamBean.passAttributeListener}"
        ajax="true" update="someAttributeId">
        <f:attribute name="someAttributeHolder" value="THIS is VALUE_OF_ATTRIBUTE !!!" />    </p:commandButton>
case 3: 
 <p:commandButton value="Pass Property"
       ajax="true" update="somePropertyId">
       <f:setPropertyActionListener target="#{PassParamBean.someProperty}" 
           value="THIS is VALUE_OF_PROPERTY !!!" />
</p:commandButton>

in managed  bean:
 package passvalue;

import java.io.Serializable;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

public class PassParamBean implements Serializable {
    private static final String DEFAULT_OUTCOME = "pass_value";

    private String someParam;
    private String someAttribute;
    private String someProperty;

    public String passParam() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        Map<String, String> params = externalContext.getRequestParameterMap();
        someParam = params.get("someParamHolder");

        return DEFAULT_OUTCOME;
    }

    public void passAttributeListener(ActionEvent event) {
        UIComponent component = event.getComponent();
        Map<String, Object> attrs = component.getAttributes();
        someAttribute = (String) attrs.get("someAttributeHolder");
    }

// setters and getters

}