Should I have a bean for every form, datatable etc in JSF?
For example, I have a form for registration, which simply has 2 fields and a button which are: nickname, password, submit
Should submitting this form go to a RegistirationFormBean or somewhere in UserBean or UserServiceBean?
What is the best practice?
Thank you.
To decide whether or not you should create a @ManagedBean
exclusively for a component of the page (e.g. form, datatable), I believe you should think about the modularity
of your design.
The 1st question you should ask yourself is: Will the component be re-used in many pages?
. For example, on sensitive pages such as ChangePassword
or DeleteAccount
, usually, you will ask the user to enter the current password to validate his identity before performing any logic. In this case, you should definitely have an exclusive bean for the validating password component so that you can re-use the component again and again without having to re-code the validating function every time.
Secondly, I usually use @ManagedBean
as a place to hold all the related functions that work toward the same goal. This grouping of functions can be pretty subjective. For example, I can have a page called CreateProduct.xhtml
with a bean called CreateProductBean
that has all the functions for creating a product. In this case, it's like 1 bean per view
. Another way is to have a bean called ProductManager
that has functions for everything related to the Product
object (i.e. create, read, update, remove). In this case, it's like 1 bean for many views
(e.g. CreateProduct.xhtml
, RemoveProduct.xhtml
). For ease of future maintenance and division of work, I usually use 1 bean per view
. The 2nd approach 1 bean for many views
is also good on certain situations but I suddenly cannot think of an example yet :P... I will update my answer when I got a good one ;).
Thirdly, I prefer to follow the 3-tier MVC model and separate back-end logic away from the front-end. For example, to persist a new account in the database, I will inject an @EJB
or a @WebServiceRef
to ask the back-end system to perform the necessary logic. It's definitely more maintenance friendly in the future :).
So, using your RegisterAccount
example, I will have
UserExistenceValidator
to check if a nickname
exists in the database. During registration, I can throw an error if the user chooses a nickname
that is taken. I can also use this bean to check if a user exists in the AddFriend.xhtml
page.RegistirationFormBean
to capture a user's inputs and talk to the back-end to persist the new account.