21
votes

Say I have an Entity class, Car. 

@Entity
public class Car

My IDE lets me automatically generate session beans from entity classes, so I end up with a CarFacade

@Stateless
public class CarFacade

I can also generate JSF Managed beans

@ManagedBean     
@RequestScoped
public class RegistrationController

I can understand the meaningful difference between the Entity class and other beans, but what are the differences between a stateless session bean and a managed bean? I read that a stateless session bean is for implementing your business logic that operates on the entities and managed beans are for interacting with the web-based front-end, by having the webpage call methods on the managed bean, and having the managed bean call business methods on the session bean.

So in my example, the RegistrationController would feature a +register(String carRegistration) method that the webpage would call. The RegistrationController would in turn instantiate a Car and call +create(Car car) on the session bean, which would persist it.

Is this correct?

1

1 Answers

27
votes

The JSF managed bean is the glue (controller) between the entity (model), the JSF page (view) and the enterprise bean (business service).

So, yes, you are basically right in your understanding that the JSF page should invoke the managed bean's action method which should in turn delegate the model and the action further to the business service and eventually handle the navigation outcome based on the result of the service call.

But you are not entirely right in how the model should be used and passed around. Usually you make the model a property of the managed bean so that you can just bind it to the form's input elements and finally pass it unchanged through to the business service.

E.g.

<h:inputText value="#{registrationController.car.make}" />
<h:inputText value="#{registrationController.car.model}" />
<h:inputText value="#{registrationController.car.year}" />
<h:commandButton value="Save" action="#{registrationController.save}" />

with

private Car car;
private @EJB CarFacade carFacade;

public RegistrationController() {
    this.car = new Car();
}

public String save() {
    carFacade.create(car);
    return "someoutcome";
}

// ...