This question already has answers here:
Difference between managed bean and backing bean
(11 answers)
Closed 7 years ago.
I am learning Java EE 6 and I am trying to grasp the overall image of it. I am reading about JSF and how adding components. I am setting/reading values from the components to a bean which has the #ManagedBean annotation.
I have some trouble understanding it properly. What is Managedbeans? Is it just just objects that holds the state of the components? And they can have other methods as well? Where does the EJBs fit in? Does the managed beans invoked methods on the EJBs?
What is Managedbeans? Is it just just objects that holds the state of
the components?
A JSF Managed bean is like any other Java bean except that if it managed by JSF. In other words it is a bean that is created and destroyed by JSF as needed.
Hortsman Core JSF 2 book states.
The JSF implementation does the following:
Creates and discards beans as needed (hence the term “managed
beans”)
Reads bean properties when displaying a web page
Sets bean properties when a form is posted
And they can have other methods as well?
Yes they can have as many methods as you may want.However you would (and should) ideally like to have your managed bean as lean as possible.For example it might have a search method but you should not be doing actually search inside this method but this search methods sole purpose should be to delegate the task to the business layer (which may or may not be EJB based) . I other words no heavy lifting .
Where does the EJBs fit in?
EJB is your Business tier , they have big biceps and do all the heavy lifting. Since EJB3 JPA was introduced and that is also part of EJB. JPA however is the persistence tier. All EJBs except for JPA run in inside an EJB container. All Java EE complaint server provide these .
In a typical 3 tier architecture (these days however it is mostly more than 3 but 3 tiered is easier to explain. JSF is your Web tier , EJBs are your business tier and JPA which is also part of EJB specification but does not need EJB container is your ORM or Persistence tier.
Do not worry about word container too much you will get used to it quickly and rarely you will have to worry about it. If you are using a Java EE server it's all setup for you.
Does the managed beans invoked methods on the EJBs?
Yes as explained above already . All the heavy lifting here. However it is not mandatory to use EJB with JSF. You could use any other framework e.g Spring or could even write simple pojos but thats an other area of discussion.
From this link JSF - Managed Beans
Managed Bean :
Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a java bean managed by JSF framework.
From this link Creating and Using a Backing Bean for a Web Page
Backing Bean :
In JSF, backing beans are JavaBeans used mainly to provide UI logic and to manage data between the web tier and the business tier of the application (similar to a data transfer object). Typically you have one backing bean per JSF page. The backing bean contains the logic and properties for the UI components used on the page.
NB:
For a backing bean to be available when the application starts, you
register it as a managed bean with a name and scope
Related
There is lot of information about Stateless, Stateful and Sigleton beans everywhere but almost nothing about javax.annotation.ManagedBean. At a first look I assumed that It's be similar to Spring's #Component but I can't use it without complete information.
If I annotate a class with #javax.annotation.ManagedBean will it be singleton or it will have instance pool like stateless?
Will the methods inside such class be concurrent? I should make sure as in a singleton they are synchronized by default.
I was thinking of annotating my DAO class with this but the #javax.enterprise.context.*; scopes put me doubt. I think #Stateless will be better. Any comments?
If not on DAO or service classes, where does this annotation fit in?
This answer gives very good explanation but doesn't answer the above questions.
Neither. They are per lookup/injection instances, more like stateful.
No, there is no container-managed concurrency.
(and 4.) Do you need transaction, security, or other EJB capabilities? Then #Stateless is probably better. Otherwise, I would just use CDI since it is better than the #javax.annotation.ManagedBean annotation in nearly all ways, and it is enabled by default in EE 7, so it is clearly the forward direction for EE.
As a bit of background, the #javax.annotation.ManagedBean annotation was added late in the development of the EE 6 cycle, and it is not widely used. The managed bean spec was intended to unify the lifecycle, injection, and naming behaviors of the EJB, CDI, and JSF managed bean component models. That was useful, but in my opinion, the #javax.annotation.ManagedBean annotation was just an afterthought to allow developers to access the minimal component model functionality without the overhead/complexity (real or perceived) of the other component models (EJB necessarily has a fixed set of required services and associated overhead, CDI is better in nearly all ways but is clearly more complex, and JSF managed beans are tied to WAR). However, this "common denominator" is then a quite limited component model with just #PostConstruct, #Resource (and other EE injection), and #Interceptors. There's no security, transaction, scoping/lifecycle (as in EJB or CDI), #PreDestroy, tight integration with the web tier, etc.
I'm a little confused by the mixed use of JSF2+Spring+EJB3 or any combination of those. I know one of the Spring principal characteristics is dependency injection, but with JSF managed beans I can use #ManagedBean and #ManagedProperty anotations and I get dependency injection functionality. With EJB3 I'm even more confused about when to use it along with JSF or if there is even a reason to use it.
So, in what kind of situation would it be a good idea to use Spring+JSF2 or EJB3+JSF2?
Until now I have created just some small web applications using only JSF2 and never needed to use Spring or EJB3. However, I'm seeing in a lot of places that people are working with all this stuff together.
First of all, Spring and EJB(+JTA) are competing technologies and usually not to be used together in the same application. Choose the one or the other. Spring or EJB(+JTA). I won't tell you which to choose, I will only tell you a bit of history and the facts so that you can easier make the decision.
Main problem they're trying to solve is providing a business service layer API with automatic transaction management. Imagine that you need to fire multiple SQL queries to perform a single business task (e.g. placing an order), and one of them failed, then you would of course like that everything is rolled back, so that the DB is kept in the same state as it was before, as if completely nothing happened. If you didn't make use of transactions, then the DB would be left in an invalid state because the first bunch of the queries actually succeeded.
If you're familiar with basic JDBC, then you should know that this can be achieved by turning off autocommit on the connection, then firing those queries in sequence, then performing commit() in the very same try in whose catch (SQLException) a rollback() is performed. This is however quite tedious to implement everytime.
With Spring and EJB(+JTA), a single (stateless) business service method call counts by default transparently as a single full transaction. This way you don't need to worry about transaction management at all. You do not need to manually create EntityManagerFactory, nor explicitly call em.getTransaction().begin() and such as you would do when you're tight-coupling business service logic into a JSF backing bean class and/or are using RESOURCE_LOCAL instead of JTA in JPA. You could for example have just the following EJB class utilizing JPA:
#Stateless
public class OrderService {
#PersistenceContext
private EntityManager em;
#EJB
private ProductService productService;
public void placeOrder(Order newOrder) {
for (Product orderedproduct : newOrder.getProducts()) {
productService.updateQuantity(orderedproduct);
}
em.persist(newOrder);
}
}
If you have a #EJB private OrderService orderService; in your JSF backing bean and invoke the orderService.placeOrder(newOrder); in the action method, then a single full transaction will be performed. If for example one of the updateQuantity() calls or the persist() call failed with an exception, then it will rollback any so far executed updateQuantity() calls, and leave the DB in a clean and crisp state. Of course, you could catch that exception in your JSF backing bean and display a faces message or so.
Noted should be that "Spring" is a quite large framework which not only competes EJB, but also CDI and JPA. Previously, during the dark J2EE ages, when EJB 2.x was extremely terrible to implement (the above EJB 3.x OrderService example would in EJB 2.x require at least 5 times more code and some XML code). Spring offered a much better alternative which required less Java code (but still many XML code). J2EE/EJB2 learned the lessons from Spring and came with Java EE 5 which offers new EJB3 API which is even more slick than Spring and required no XML at all.
Spring also offers IoC/DI (inversion of control; dependency injection) out the box. This was during the J2EE era configured by XML which can go quite overboard. Nowadays Spring also uses annotations, but still some XML is required. Since Java EE 6, after having learned the lessons from Spring, CDI is offered out the box to provide the same DI functionality, but then without any need for XML. With Spring DI #Component/#Autowired and CDI #Named/#Inject you can achieve the same as JSF does with #ManagedBean/#ManagedProperty, but Spring DI and CDI offers many more advantages around it: you can for example write interceptors to pre-process or post-process managed bean creation/destroy or a managed bean method call, you can create custom scopes, producers and consumers, you can inject an instance of narrower scope in an instance of broader scope, etc.
Spring also offers MVC which essentially competes JSF. It makes no sense to mix JSF with Spring MVC. Further Spring also offers Data which is essentially an extra abstraction layer over JPA, further minimizing DAO boilerplate (but which essentially doesn't represent the business service layer as whole).
See also:
What exactly is Java EE?
JSF Controller, Service and DAO
#Stateless beans versus #Stateful beans
There's no real easy answer here as Spring is many things.
On a really high level, Spring competes with Java EE, meaning you would use either one of them as a full stack framework.
On a finer grained level, the Spring IoC container and Spring Beans compete with the combination of CDI & EJB in Java EE.
As for the web layer, Spring MVC competes with JSF. Some Spring xyzTemplate competes with the JPA interfaces (both can use eg Hibernate as the implementation of those).
It's possible to mix and match; eg use CDI & EJB beans with Spring MVC, OR use Spring Beans with JSF.
You will normally not use 2 directly competing techs together. Spring beans + CDI + EJB in the same app, or Spring MVC + JSF is silly.
This question already has answers here:
What is a JavaBean exactly?
(23 answers)
Closed 6 years ago.
I was searching for difference between javabean and servlet. I found
Servlet corresponds a Controller
JavaBean corresponds a Model
and
java bean is a reusable component,where as the servlet is the java
program which extends the server capability
Now, what does re-usable means in javabean. Can't we re-use servlet ?
I will appreciate, if anyone can explain this, with few examples.
Servlets and JavaBeans are completely different concepts. The servlet API provides for servicing Internet requests, typically from client browsers but not limited to that.
JavaBeans are a component architecture for encapsulating functionality. A typical use would be a bean used by a servlet to handle database inquiries, but bean architecture is used in lots of places.
Sessions are the servlet mechanism for storing objects related to a particular user, these objects may or may not be beans. Beans used to create user interfaces (with your clever IDE) have more stringent requirements. Beans used in servlets and JSP are typically simpler.
Making it more straight, JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc.
So, both have nothing in common except Java.
JavaBeans and Servlet are both concepts part of the Java EE (Java Enterprise Edition) package release in 1999/2000.
The servlet is a Java class (used as an Controller) in a java Web Application. Its role is to manage the HTTP Request and generate an HTTP Response. The Servlet is using JavaBeans to get its information from the database for instance.
The JavaBean is a simple java class used to represent the model of your application. To be called a JavaBean, the class must have public getters and setters for all its properties, must have a no-argument constructor, and must be serializable.
It is interesting to understand that this simple JavaBean concept migrates to the Enterprise Java Bean (EJB) in early 2000. But experience proved that EJBs were quite complicated to managed in the Java EE environment. Consequently, Enterprise JavaBeans were mostly replaced by "Pojos" (Plain Old Java Object) popularized by IOC Containers (like Spring in 2003). IOC pulled back Javabean to its former concept. IOC replaced the overall EJB-J2EE Templating pattern, Service Locator, Business Delegate patterns to a simple Injection of Dependencies (DI).
They are two completely different things.
A servlet is used for handling requests in a web application, so yes it is similar to a controller.
A Java bean is any java class that adheres to a set of rules, see: What is a "Java Bean"?
I guess whatever you are reading is telling you how each fit into the MVC pattern
The Life cycle of Servlet manage by Web container where In case of Java Bean you are initialize or initiate your java Bean.
There are two type of servlet, Generic Servlet which support different type of protocol request where HTTPServlet which support HTTP protocol.
In most of the framework like struts/Spring, they use servlet as controller to take the request call and depends on the configuration, it's divert the call to different Action Class/Action Controller
Java bean is a data access object which is used to interact with the database.Java bean is a POJO (Plain Old Java Object).A servlet is used with the JSP, like an interface for JSP.
Both java bean and Servlet are part of the MVC.
I'm working on a project using JSF 1.2 deploying a portlet to WebSphere Portal Server 6.1 on top of WAS 7. For various contractual/political reasons, we're stuck with JSF 1.2.
However. we are using Spring beans throughout our application in order to get AoP logging.
It is somewhat annoying that we can't use JSF 2.0. In particular, view scope would be ideal for our app. It will be a high usage site and keeping all the page beans in session scope is wasteful and I'm sure will cause raised eyebrows from our non-functional testing team later on.
It occurred to me that I could emulate View Scope by using Spring's custom scope and a custom JSF component that simply maintains a map of active beans set by the Spring scope and attaching this component on our pages. Together with a custom variable resolver that can find beans in this map, we should be able to emulate view scope
(Our journey is only four pages, but each page has a few postbacks to the same page)
How does this approach sound? I want to be sure I'm not somehow shooting myself in the foot before I present this to my project colleagues and dash off and start ripping apart the bean code we've already written.
Not sure about Spring, but for JSF 1.2 managed beans, the Tomahawk's <t:saveState> was the way to let a JSF 1.2 request scoped bean behave (almost) exactly like JSF 2.0 view scoped bean. Almost, because the destroying of the view and the state saving is a bit more efficient in JSF 2.x. But the effect is ultimately the same.
All you need to do is referencing the bean by that tag elsewhere in the view:
<t:saveState value="#{bean}" />
This question already has an answer here:
Difference between Request MVC and Component MVC [closed]
(1 answer)
Closed 6 years ago.
I haved used Struts framework in all my past applications and for the new application,my client has requested to use either Spring MVC or JSF? I am not familiar with these two frameworks but our timelines are strict. So, I am not sure which framework I will choose to build the application.
Can anyone please suggest me which framework will be easy to learn in quick time?
Thanks
Of course, it's going to be different for everyone, but I'd suggest Spring MVC, as it's a request-based framework like Struts. Of course, you'll want to learn about core Spring stuff like Inversion of Control / Dependency Injection (but I'd consider that a plus...) and whatever you're going to use for database access (just JDBC? Hibernate? iBatis? etc.).
JSF is component-based, which is a bit different paradigm from request-based frameworks. If you do plan to go the JSF route, I'd suggest looking at Seam from JBoss. It's more of a front-to-back framework that uses JSF as the web/presentation end and EJB as the backend. And pretty much all the people who've used it claim it makes JSF and EJB more usable than they are by themselves.
Good luck on whichever technology you choose, though. (Sounds like you'll need it - strict timelines and a client that's prescribing web frameworks?)
I'd suggest SpringMVC, because of the timeframe:
you need something with less steep learning curve. SpringMVC is more like Struts than JSF
in order to use the power of JSF you need to get familiar with many "tricks", while SpringMVC is more or less straightforward
I'd suggest JSF + Primefaces component library. I am using this combination to build most of our projects. As I remember, I spent one week to learn the technology and finished my first project in one month. The development time at least 30% faster than Struts.
SpringMVC is not a bad technology and it's quite popular.
Really depends on which one your like the most.
JSF is just the view layer of the MVC and wil need to be used with other technologies like Spring/Hibernate or EJB for a full MVC.
I have been using the Spring MVC for about 1 months now, whilst it's probably not the latyest version of SpringMVC I've found it a little annoying that we have so much XML to deal with. All the managed beans and DAO has XML config to it. Also everything seems to have to go thorugh a method called onSubmit().
JSF with something like EJB is far simplier in my opinion... Everything can be done using Annotations so simply use #ManagedBean=theBean in your backing bean and in your JSF put {thebean.param} and you have access to the backing bean's data. Also you can use the Session beans of your EJB as the backing beans for JSF then have direct acces to the DAO (Model layer) Entity bean. Again simply by using the #Entity annotation and the EntityManager class
Spring MVC is a web framework inside the Spring framework. It does provide features as those in JSF 2.0:
ajax-support
validation
dependency-injection etc
Yet, you can use Spring (not Spring MVC) together with JSF 2.0, with spring providing the dependency-injection, aop, transaction management mechanisms, and JSF providing the web layer.
Of course, you'll want to learn about core Spring stuff like Inversion of Control / Dependency Injection (but I'd consider that a plus...)
JSF is indeed based on IoC, and much simpler than the Spring learning curve.