using more than one managed bean in same jsf page - jsf

If I have page, lets say includes two different customers informations, how can I use two different managed beans (which is same java class) in the same page?
As a summary, in the same page I want to hold information of one customer in one bean, another in another bean.

I want to hold information of one customer in one bean, another in
another bean.
Another bean for same purpose is duplication, and If you are thinking it logical. Every page have its page's state (life). when you try #{bean.customer} it will return same value. Because its object is same.
I would suggest to improve your code use another class for the view, layer your application. like
//Base class
public class Customer {
private String id;
/*
*Other fields
*/
//getter Setters
}
#ManagedBean
#RequestScoped
public class PageBackingBean implements Serializable{
List<Customer> customer = new ArrayList<>(); //can Hold more than one customer
public PageBackingBean(){
Customer cus1 = DataBase.loadByCustomerId(id);
customer.add(cus1);
Customer cus2 = DataBase.loadByCustomerId(id);
customer.add(cus2);
}
}

Related

How to add text in Facelets

Im new to web programming so this is a beginner question.
In my web application which is a maven project with JSF framework(university project), I have some pages with just text that displays various information about my fake air line company(only consists of <p> and <h1>). Now, to my question. Should I just "hard code" the information on the JSF Page or should I use beans to get my text and titles from?
The information that will be on my info pages will remain the same and never change.
If this question is inappropriate to ask here, please let me know and Ill remove it.
Since you've stated that the information will never change, storing it in a string in the bean class would work, and use getter methods to retrieve the data
#ManagedBean
#SessionScoped
public final class Airlineimplements Serializable
{
private static final long serialVersionUID = 47493274L;
private String title = "Air Canada";
private String headquarters = "Toronto Ontario Canada";
public Airline()
{
}
public String getTitle()
{
return title;
}
public String getHeadquarters()
{
return headquarters;
}
}
This is #RequestScoped so that you retrieve the information on each request and the information is garbaged after the request.
A #RequestScoped bean will be garbaged by end of every request and recreated on every new request.
Full answer here about #ViewScoped vs #RequestScoped
Difference between View and Request scope in managed beans
Although this should be #SessionScoped which keeps the information for the life of the session.
For the Serializable UID, the serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to ensure that the caller and receiver of a Serialized object have the same loaded classes.
More information about Serializable
http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
Here are some additional tutorials on JSF for beginners
http://www.tutorialspoint.com/jsf/
http://www.vogella.com/tutorials/JavaServerFaces/article.html

jsf cdi application architecture

I have an architecture problem with the following use case.
I have a JSF page for creating JPA entities, for example orders.
The Order entity has two fields: invoiceRecipient and receiver. Both of the type Customer.
There are two fields on the Order form, each with a button that opens a selection list for choosing a customer from the customerSelectionController.
when the customer has been chosen the customerSelectionController bean does something like:
#Inject
#Selected
Event<Customer> customerSelectedEvent;
public void select(Customer customer) {
customerSelectedEvent.fire(customer);
}
and the orderFormController reveives the event with
public void customerSelected(#Observes #Selected Customer customer) {
}
and here is the problem ^^
The orderFormController knows the customer has been selected but is it intended to be set as the invoiceRecipient or as the receiver of the order?
I know you could specify more accurate qualifiers like #SelectedAsInvoiceRecipient but is this really the way how to do this?
Should I copy the customerSelectionController bean as an invoiceRecipientSelectionController and a receiverSelectionController and let both of them fire differently qualified Customer entities?
I am also using Apache Deltaspike that supports GroupedConversations and other complex things, but I couldn't find a specified rule how to achive this.
Thanks for your help
You can either use qualifiers or wrap your Customer entity in a more specific event type, e.g.
public class InvoiceRecipientSelected {
private Customer customer;
// ... add accessors ...
}
Event<InvoiceRecipientSelected> invoiceRecipientSelected;

jsf 2 best one managed bean multiple views

I`m kind of noob to JSF and I'm trying to figure out which would be the most elegant solution for the following scenario:
Let's say that I have a user managed bean called UserMB:
#ManagedBean
public class UserMB {
private User user;
private List<User> users;
// getters and setters here
public void addUser(User user){
// do add user logic here
}
public List<User> listAllUsers(){
// do list All users logic here
}
#PostConstruct
private void init(){
// populate List<user> users - for the listAllUsers scenario
}
}
Let`s assume that i do not have a form to submit directly to listAllUsers() method, but instead i want to see all users when I open the page list-all-users.xhtml.
When I hit the managed bean from addUser.xhtml a query will be performed to DB to load all users because the bean will not know if i want to use listAllUsers() method or addUser() method.
Should i split this functionality in 2 managed beans ?
Because if so I would have to create several managed beans to deal with "User" business (ie. in Struts2 i would have only one Action that would take care of all user interactions).
P.S. I know that there is the solution to populate List in getter method but I read one article of BalusC that advise us not to do this...
Should i split this functionality in 2 managed beans ?
Yes. Use one bean per view/form. Keep the backing bean class as slick as possible. Don't give it too much responsibilities.

Can a managed bean extends a DTO

I have 2 classes (managed beans) in my business that of type X, the 2 classes merely have the same attributes except for 3 attributes, can i make a DTO contains all the attributes in the 2 beans and let them extends this DTO or i have to group the attributes in the DTO and associate it with the 2 beans so that each bean could set and get its attributes, i want to know the appropriate solution from the point of design, another question is it a correct design for the managed bean and the DTO to have a relation directly.
You could do that but it'd be error-prone, violating the MVC paradigm and simply a bad practice as far as I'm concerned.
Consider and compare two simple cases. First case is a bean extending a DTO and the second case is a bean containing a DTO.
Managed bean that extends a DTO
public class ContactDto {
private String name;
}
public class ContactBean extends ContactDto {
//has name inherited
private boolean renderedAdminPanel;
public void action { }
}
In this case who will be producing managed beans? When will they be instantiated and how? Will your DAO be tightly coupled with ContacyBean? What if you decide to give up using DTOs and use detached entities instead?
All of it increases discrepancies in your architecture and makes it at the very least less manageable.
Now let's consider the alternative approach.
Managed bean that contains a DTO
public class ContactBean {
private ContactDto contactDto;//all fields contained inside
#PostConstruct
public void init() {
//get data from your service based on injected parameter's value and assign it to your DTO
}
private boolean renderedAdminPanel;
public void action { }
}
In this case all logics is crystal clear. Also, you don't need to write 'extras', because all of your properties will be available in EL context with an additional accessor. Your object's lifecycle is predictable and well-formed.
Ultimately, a DTO is a DTO and you wouldn't like to spice it up with additional and possibly secure information, like injected current user, contexts, session variables, etc. to pass that information around. Keep it simple and in its own place.

How can i send a parameter to be used in the #PostConstruct method of a backing bean?

I need to preload some data to be displayed when the page loads. The initialization steps are performed on a #PostConstruct-annotated method but now i need to use a parameter in order to get the data.
What i'm trying to do:
#PostConstruct
public void init()
{
List data = getDataFromDB(parameter) /*Need to read a parameter created somewhere else*/
}
Is there a way to achieve this?
Thanks in advance
It's kind of hard to say what you mean by "a parameter set somewhere else". I will assume that "somewhere else" means "sent from browser by HTTP". In such case you should create a standard property in your managed bean and:
in JSF 2.0 you could annotate it with #ManagedProperty("#{param.nameOfParameterToRead}")
in JSF 1.2 and less - use managed-property element in your bean description (faces-config.xml).
Like this:
#ManagedBean
#RequestScoped
class MyManagedBean {
#ManagedProperty("#{param.id}")
public Integer id;
#PostConstruct
public void init(){
data = getDataFromDB(id)
}
// setters and getters (mandatory, even though annotation is on an attribute!!!)
}
Careful: injecting properties does not use JSF converters, so it is best to inject strings and take care of conversion in your own code.
how about reading from Properties file, or fetching List from DB ??

Resources