Question

I am working on a Web-application using JavaServer Faces.

I have found many examples and tutorials on how to use JavaServer Faces, but none of them actually explain what a Bean is used for. My initial thoughts were, that Beans represent forms. You enter data into your form and click the submit button and the associated Bean is filled with the data and a method is called.

However, so far I have only seen examples where there is one Bean per page, so a Bean could also represent a page and thus contain multiple forms.

I am also confused about the scope of a Bean. If the Bean represents a form or a page, it should become invalid after the request ended. If you make the bean live in the scope of the session, what happens to the Bean? Are you still able to somehow get the data out of it or will it just fill the associated form for you once you go back to it?

In summary - what is a Managed Bean and how do you use it properly?

Était-ce utile?

La solution

A bean is a managed bean when you never need to manage the bean instance yourself as in by manually doing someScopedMap.put("bean", new Bean());. The framework takes care of this. This has nothing to do with whether the page contains a form or not. You're basically telling the framework "Hey, here's a backing bean class com.example.Foo. You may use it as managed bean with name "foo" and put it in scope X whenever an EL expression references it via #{foo}", without the need to do that all yourself. The framework (JSF, CDI, Spring, etc) manages it all by itself.

As to the choosing the right scope, that logically depends on the scope the data needs to be kept in. For example, you obviously don't want to store submitted form data in application scope. Any other visitor of the website would otherwise see it. Just think logically and read How to choose the right bean scope?

As to "one bean per form" or "one bean per page" concept, this is actually subjective as both can technically work equally good, but as to maintainability it's strongly recommended to make your classes as slick as possible, including backing beans. Therefore the "one bean per form" is the better practice. Don't throw completely different responsibilities together in a single class. Law of demeter and such. Beans can easily access each other using @Inject or @ManagedProperty.

See also:

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top