Im currently using JSF2, and i notice the JSF bean could have a lot of responsibility, and if combined will look like lots of codes. These include :
holding the state / data
could be a backing bean for the UI component
action methods definition
action listener methods definition
navigation
calling the services
all the setter n getters
Does it make anysense to break these into several classes or do you usually combine all of them together ?
Currenly for every JSF Bean, i define another class to hold the view data / state along with the setter getters.
How do you usually do it ? Please share your experience !
Thank you =)
Every property which is been used in action(listener) methods needs to stay in the backing bean. The remnant most likely belongs in its own class which can in turn be a different (managed/entity)bean, eventually as a (managed)property of the bean where it originated.
Related
I recently read this article from Neil Griffin Making Distinctions Between Different Kinds of JSF Managed-Beans and it got me thinking about the distinction between different beans in my own application. To quickly summarise the gist:
Model Managed-Bean: This type of managed-bean participates in the
"Model" concern of the MVC design pattern. When you see the word
"model" -- think DATA. A JSF model-bean should be a POJO that follows
the JavaBean design pattern with getters/setters encapsulating
properties.
Backing Managed-Bean: This type of managed-bean participates in the
"View" concern of the MVC design pattern. The purpose of a
backing-bean is to support UI logic, and has a 1::1 relationship with
a JSF view, or a JSF form in a Facelet composition. Although it
typically has JavaBean-style properties with associated
getters/setters, these are properties of the View -- not of the
underlying application data model. JSF backing-beans may also have JSF
actionListener and valueChangeListener methods.
Controller Managed-Bean: This type of managed-bean participates in
the "Controller" concern of the MVC design pattern. The purpose of a
controller bean is to execute some kind of business logic and return a
navigation outcome to the JSF navigation-handler. JSF controller-beans
typically have JSF action methods (and not actionListener methods).
Support Managed-Bean: This type of bean "supports" one or more views
in the "View" concern of the MVC design pattern. The typical use case
is supplying an ArrayList to JSF h:selectOneMenu drop-down
lists that appear in more than one JSF view. If the data in the
dropdown lists is particular to the user, then the bean would be kept
in session scope.
Utility Managed-Bean: This type of bean provides some type of
"utility" function to one or more JSF views. A good example of this
might be a FileUpload bean that can be reused in multiple web
applications.
This made sense to me and for the past few hours I have been refactoring my code and came up with the following with respect to the user login:
The AuthenticationController is an example of a Controller Managed-Bean. It is request-scoped and features two getters and setters for setting a username and password, and two navigation methods, authenticate and logout, navigating the user to either their private area upon successful login, or back to the main page when logging out.
The UserBean is an example of a Support Managed-Bean. It is session-scoped and features an instance of User class (which would be null when you are not authenticated) with a getter and setter, nothing more.
The AuthenticationController has this user as a managed property (#ManagedProperty(value = "#{userController.user} private User user;). Upon successful authentication, the AuthenticationController would set the managed property to the actual user instance with the corresponding username that was used for the login.
Any new beans would be able to grab the user as a managed property as well and pull the data they need, such as group membership for instance, if the User class would feature a list with group names.
Would this way be the proper way to go about with regard to the seperation of concerns?
This is a very subjective question. I personally disagree that article and find that it's giving really bad advice to starters.
Model Managed-Bean: This type of managed-bean participates in the "Model" concern of the MVC design pattern. When you see the word "model" -- think DATA. A JSF model-bean should be a POJO that follows the JavaBean design pattern with getters/setters encapsulating properties.
I would absolutely not make or call it a managed bean. Just make it a property of a #ManagedBean. For example a DTO or JPA #Entity.
Backing Managed-Bean: This type of managed-bean participates in the "View" concern of the MVC design pattern. The purpose of a backing-bean is to support UI logic, and has a 1::1 relationship with a JSF view, or a JSF form in a Facelet composition. Although it typically has JavaBean-style properties with associated getters/setters, these are properties of the View -- not of the underlying application data model. JSF backing-beans may also have JSF actionListener and valueChangeListener methods.
This way you keep duplicating and mapping the properties of the entity in the managed bean. This makes no sense to me. As said, just make the entity a property of the managed bean and let the input fields refer it directly like #{authenticator.user.name} instead of #{authenticator.username}.
Controller Managed-Bean: This type of managed-bean participates in the "Controller" concern of the MVC design pattern. The purpose of a controller bean is to execute some kind of business logic and return a navigation outcome to the JSF navigation-handler. JSF controller-beans typically have JSF action methods (and not actionListener methods).
This describes the #RequestScoped/#ViewScoped #ManagedBean class pretty much. Whether event listener methods are allowed or not depends on whether they are specific to the view which is tied to the bean and/or are for their job dependent on the bean's state. If they are, then they belongs in the bean. If not, then they should be a standalone implementation of any FacesListener interface, but definitely not a managed bean.
Support Managed-Bean: This type of bean "supports" one or more views in the "View" concern of the MVC design pattern. The typical use case is supplying an ArrayList to JSF h:selectOneMenu drop-down lists that appear in more than one JSF view. If the data in the dropdown lists is particular to the user, then the bean would be kept in session scope.
Fine. For application wide data like dropdown lists just use an #ApplicationScoped bean and for session wide data like logged-in user and its preferences just use a #SessionScoped one.
Utility Managed-Bean: This type of bean provides some type of "utility" function to one or more JSF views. A good example of this might be a FileUpload bean that can be reused in multiple web applications.
This makes not really sense to me. Backing beans are usually tied to single views. This sounds too much like an ActionListener implementation which is to be used by <f:actionListener> in command components to your choice. Definitely not a managed bean.
For kickoff examples of the right approach, see also:
Hello World example in Our JSF wiki page
"Bookstore CRUD" example in this answer
"Master-detail" example in this answer
JSF Service Layer
Communication in JSF 2
When a JSF form field is wired into an entity bean field (which is mapped to a DB field), each setter in the entity bean is called regardless of whether the user changed the form field value in the front end, i.e. the setters on unchanged fields are invoked the same as those that have changed but their new value is the same as the old value.
My question is simple: Is there a way to configure JSF to only call the setters mapped to the fields that have changed in the front end? The reason for this is that I have a requirement by which I have to detect deltas on every persist and log them, more about which can be read in this question.
Maybe I didn't understand you clearly, but why are you mapping directly your entity beans to a JSF view ?! IMHO it would be better if you add managed beans between your JSF pages and the entities in order to better separate your business logic from data access.
Any way, I think the easiest solution to impelement for that case is by making use of Value Change Events which are invoked "normally" after the Process Validations phase (unless you make use of the immediate attribute).
The good news about Value Change Events (regarding your example) is they are invoked ONLY after you force form submit using JavaScript or Command components AND the new value is different from the old value.
So, as an example on how to use value change listeners, you can add valueChangeListner attribute to each of your JSF tags like following:
<h:inputText id="input" value="#{someBean.someValue}"
valueChangeListener="#{someBean.valueChanged} />
Then, implement your valueChanged() method to look something like:
public void valueChanged(ValueChangeEvent event) {
// You can use event.getOldValue() and event.getNewValue() to get the old or the new value
}
Using the above implementation, may help you to separate your logging code (it will be included in the listeners) from your managed properties setters.
NB: Value Change Listeners may also be implemetend otherwise using the f:valueChangeListener Tag, but this is not the best choice for your example (you can find some examples in the section below, just in case)
See also:
Valuechangelistener Doubt in JSF
JSF 2 valueChangeListener example
When to use valueChangeListener or f:ajax listener?
I have three screens(views) associated with separate managed beans for each view.
And, I have a common pop-up dialog which can be opened in all the views.
Can I define a managedbean separately for the pop-up with state #NoneScoped; and maintain an instance of it in each parent bean?? or
Do I need to maintain pop-up data in all three parent views?
Please, suggest me the best practice.
I think this is what you are looking for (check out the answer by BalusC) -
Whats the correct way to create multiple instances of managed beans in JSF 2.0
And since you are using #NoneScoped (unlike #RequestScoped in the above question), I also recommend you to look at this answer by BalusC (about #NoneScoped) -
what is none scope bean and when to use it?
And according to this answer, you can't maintain any instances of a managedbean that is none-scoped, as they are garbaged as soon as they are used.
So, in your case since you have three separate views, for each view, the bean is constructed and used to build the view and garbaged. (Looks like it does not even last for a request cycle). When you request another view, it will be a separate instance.
To have multiple intances of a bean, you can have three properties in a Session-Scoped been (to make them survive across multiple views).
#ManagedBean
#SessionScoped
public class Parent {
private Child child1;
private Child child2;
private Child child3;
// ...
}
I can't find any guidance on this question. I am writing a composite component that needs its own backing bean because it interacts with a data base.
The new component also needs to be able to set a value in some other backing bean as the result of some user action.
To do this, the question is do I have to write a #FacesComponent java class or a regular #Model/#Named (I use CDI annotations) type of bean? If you can use either, what is the advantage of one or the other?
Secondary question: will I be able to use CDI #Inject into a #FacesComponent to get my DAOs and such?
Update: I discovered that I can access cc.attr objects with the following code in a regular backing bean:
FacesContext fc = FacesContext.getCurrentInstance();
Object obj = fc.getApplication().evaluateExpressionGet(fc,
"#{cc.attrs.model.location}", Location.class);
So this allows me to obtain attributes. I haven't found out how I can write them yet.
So it seems that the only real reason to do a #FacesComponent is if you want to write rendering code that will output something the normal Facelets tags won't render. Is this correct?
I think BalusC responded to this basic question in this thread.
The main advantage is the ability of a #FacesComponent to access attributes that a UIComponent normally has access to, rather than trying to tie in with EL expressions executed in the bean.
Hey guys. I'm designing a site that uses the Icefaces framework. I've been reading a book called Real World Java EE patterns. I'm kind of confused how to layout the pages. Normally I would have just a POJO class implement serializable for a bean. This bean would then back each page. With a single page design I'm going to have a bunch of elements on the page. Datatables, trees, inputs, calendars etc. Is it normal or best practice to have separate beans for each datatable, calendar, etc or put that all in one bean? I'm not sure how to approach this. Right now each element is a bean and I'm using the #Inject annotation to have the data table talk to the tree and vise versa. This creates really bad code and if I put this as a member of the class I will get a circular reference because the data table bean has to inject the calendar and the calendar has to inject the data table.
Thanks for any help.
I tend to use a single bean per <h:form> or at least per view (XHTML/JSP file). Any related beans will just be injected in this particular "main" bean (and thus not among each other).