I've created FacesComponent which I want to initialize in constructor/postconstructor. The problem is that getAttributes()
is empty in there. Below is the example.
@FacesComponent("articleComponent")
public class ArticleFacesComponent extends UINamingContainer {
private Article article;
public ArticleFacesComponent() {
Object idObj = getAttributes().get("articleId"); // I want to get article id to initialize object but getAttributes() is empty
...
article = em.find(Article.class, id);
}
}
You need to perform the job in the encodeAll()
method. It's invoked during render response, when the component is about to be rendered.
@Override
public void encodeAll(FacesContext context) throws IOException {
// Here.
super.encodeAll(context);
}
Given that you're extending from UINamingContainer
, you're most likely creating a backing component for a composite component. In that case, this article should provide you useful insights to get started: composite component with multiple input fields.
Unrelated to the concrete problem, accessing the DB in a component is a smell. Rather pass a fullworthy Article
instance as component value instead of its ID. The component/renderer should only deal with front-end (HTTP/HTML) stuff based on the model, not with back-end (DB/SQL) stuff. You should provide the component exactly the model it needs to work with.