Tuesday, July 28, 2009

JSF Thing to cater for if you are JSF Developer

It is because JSF is component base(not simple as MVC direct request to action in controller layer).

Problem of coding style

1) DB query inside getter method of backing bean.

public List getUserRole(){
return userRoleDao.queryAllUserRole();
}


Issue : Getter may be call in restore view or apply request value or render response phase
  • Table component, it wil cause the data being query 2 times.
  • inputText/radio etc. component, it will check the previous submitted value store(JSF will store previous submitted value automatically) inside the inputText. If it is null, it will call the getter in backing bean to retrieve the value.
Following was the log.
[ INFO] 29-07-09 11:10:34 : BEFORE RESTORE_VIEW(1)
[ INFO] 29-07-09 11:10:34 : AFTER RESTORE_VIEW(1)
[ INFO] 29-07-09 11:10:34 : BEFORE APPLY_REQUEST_VALUES(2) Hibernate: select this_.role_name as ...
[ INFO] 29-07-09 11:10:34 : AFTER APPLY_REQUEST_VALUES(2)
[ INFO] 29-07-09 11:10:34 : BEFORE PROCESS_VALIDATIONS(3)
[ INFO] 29-07-09 11:10:34 : AFTER PROCESS_VALIDATIONS(3)
[ INFO] 29-07-09 11:10:34 : BEFORE UPDATE_MODEL_VALUES(4)
[ INFO] 29-07-09 11:10:34 : AFTER UPDATE_MODEL_VALUES(4)
[ INFO] 29-07-09 11:10:34 : BEFORE INVOKE_APPLICATION(5)
[ INFO] 29-07-09 11:10:34 : AFTER INVOKE_APPLICATION(5)
[ INFO] 29-07-09 11:10:34 : BEFORE RENDER_RESPONSE(6) Hibernate: select this_.role_name ...
[ INFO] 29-07-09 11:10:35 : AFTER RENDER_RESPONSE(6)

Solution : Only query DB when it is in render response phase.

public List getUserRole(){
if (FacesContext.getCurrentInstance().getRenderResponse())
return userRoleDao.queryAllUserRole();
else
return null;
}

or

public List getUserRole(){
if ( userRoleList!=null)
userRoleList = userRoleDao.queryAllUserRole();

return userRoleList;
}

JSF 2 going to have MVC lifecycle!!!

No comments: