JavaEE Spring Seam

4,091 views

Published on

comparing and application build using JavaEE, Java EE with Spring, or JavaEE with SEAM

0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,091
On SlideShare
0
From Embeds
0
Number of Embeds
104
Actions
Shares
0
Downloads
76
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • You can do o/r mapping using either java language annotations or xml descriptor or a combination of both. And the API is usable in both Java EE and Java SE environments it also supports pluggable persistence providers. So you can use the persistence provider of your choice in your app server environment, you are not locked into a persistence provider. The query language has been expanded considerably beyond the earlier EJB QL , so now its a rich full fledged query language over the object model. Object relational mapping has been standardized, which had long been requested.
  • The primary feature of the JPAis that is is a pojo based persistence model. Entities are simple java classes they are not components. They support rich modeling capabilities. They support inheritance, they support polymorphism, polymorphic relationships, polymorphic queries.
  • JPA Entities are plain old java object. You create an instance by means of new, they have no required interfaces.. An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes. The persistent state of an entity is represented either through persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store. Entities have a persistent identity, which corresponds to a primary key in a database. They may have both persistent and non-persistent state. And the persistent state can be either simple types such as java primitives, wrappers, enums, types that are serializable or the state can be complex it can be composite (dependent objects)
  • One-to-many and many-to-one bidirectional relationships . A one-to-many bidirectional relationship occurs when one entity bean maintains a collection-based relationship property with another entity bean, and each entity bean referenced in the collection maintains a single reference back to its aggregating bean. While the Order table contains a foreign key to the Customer table, the customer table doesn't maintain a foreign key back to the order table. This illustrates the separation between the entity bean's view of its persistence relationships and the database's actual implementation of those relationships. We need to add a collection-based relationship property to the customer class so that it can reference all the orders that were created for it. there must be one owning side of a relationship in a one-to-many bidirectional relationship. the many-to-one side is always the owner (the order).this requires you to call Order.setCustomer( ) whenever you add or remove a customers order. The one to many side is the non owning side and it has to say where the foreign key is and does this by using the mappedBy. The cust field in the order class is the one that maps the foreign key for this relationship, and the defaults to cust_id in the order table
  • An EntityManager instance is used to manage the state and life cycle of entities within a persistence context. The entity manager is responsible for creating and removing persistent entity instances and finding entities by the entity's primary key. It also allows queries to be run on entities.
  • An EntityManager instance is used to manage the state and life cycle of entities within a persistence context. The entity manager is responsible for creating and removing persistent entity instances and finding entities by the entity's primary key. It also allows queries to be run on entities.
  • In a transaction-scoped container managed entity manager (common case in a Java EE environment), the JTA transaction propagation is the same as the persistence context resource propagation. In other words, container-managed transaction-scoped entity managers retrieved within a given JTA transaction all share the same persistence context.
  • In this example the sb looks up an order, adds a line items. The stateless session bean does the workflow with a lookup and merge in each operation as needed, whereas the stateful session bean does the same by caching the references. Extended persistence context to keep and reuse managed entities that are the subject of the conversation workflow HTTPSession, stateful session bean Entities remain managed and cached over multiple transactions Become detached when EntityManager is closed or when Stateful session bean is removed
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • Dependency Injection With Java EE 5, invoking an EJB component is a snap with dependency injection. Dependency injection support in Java EE 5 was influenced by inversion of control (IoC) containers such as Spring. Dependency injection is essentially the opposite of the JNDI: the container is responsible for looking up and instantiating an instance of an EJB or a resource. The concept behind Inversion of Control is often expressed in the Hollywood Principle: "Don't call me, I'll call you." IoC moves the responsibility for making things happen into the framework, and away from application code. Whereas your code calls a traditional class library, an IoC framework calls your code.
  • Components - A tag for a JSF custom component - A component class (UI class) that • maintains state, • renders a user interface, • and processes input • The tag is just needed for plumbing in the JSF page • The UI class does the important work - Render the user interface by encoding markup - Process user input by decoding the current HTTP request --------------------------------- The actual UIComponent class, which defines the behavior of the component, such as UISelectOne, which allows the user to "select one from many." #An optional Renderer class, which provides specific renderings of the component. For example, a UISelectOne component could be rendered in HTML as either a group of radio buttons or a "select" menu. #A JSP tag, which associates a Renderer with a UIComponent and makes them usable in a JSP as a single tag, <h:selectOneMenu >. It's important to note that "pluggable" Renderer classes allow the UI component to not only be HTML tag-independent (radio or select), but client device—independent where the UI component can be rendered in any markup language, such as HTML, WML, and so on
  • note the taglib declaration. JSF comes with its own set of JSP custom tag libraries. Here we declare two JSF tag libraries, html and core. The html JSF tag library contains HTML rendering tags while the core JSF tag library contains JSF core tags. These libraries expose most of the JSF components, validators, event registers, and so on. Note that there are several UI components in this page. And they are <h:output_text>, <h:inputText>, <h:commandButton>. The <h:output_text>elements contains value attributes whose values come from the property values of a JavaBean called UserNumberBean. The names of these properties of this bean are called minimum and maximum. The <h:inputText> element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The <h:commandButton> displays a button that can be pressed for submitting the form data. ·form tag represents an input form with which the user can submit data to the server.
  • This slide shows the relationship between JSP page and backing bean declaration in the application configuration file. Every backing bean needs to be declared in the application configuration file. Here in this guessNumber example, there is only one bean called UserNumberBean, which has two properties called minimum and maximum whose types and initial values are also defined. In the JSP page, you refer to these properties using JSF EL expression notation like #{UserNumberBean.minimum} or #{UserNumberBean.maximum}. to provide an event-based, JavaBean model way of interacting with application data, JavaServer Faces provides an easy-to-use mechanism by which Web-accessible user interface components are bound to server-side JavaBeans that are registered as "Managed Beans" in an XML file (faces-config.xml). Beans are bound to a user interface with a simple-to-use Expression Language, which is almost identical to JSTL's Expression Language syntax.
  • note the taglib declaration. JSF comes with its own set of JSP custom tag libraries. Here we declare two JSF tag libraries, html and core. The html JSF tag library contains HTML rendering tags while the core JSF tag library contains JSF core tags. These libraries expose most of the JSF components, validators, event registers, and so on. Note that there are several UI components in this page. And they are <h:output_text>, <h:inputText>, <h:commandButton>. The <h:output_text>elements contains value attributes whose values come from the property values of a JavaBean called UserNumberBean. The names of these properties of this bean are called minimum and maximum. The <h:inputText> element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The <h:commandButton> displays a button that can be pressed for submitting the form data. ·form tag represents an input form with which the user can submit data to the server.
  • The value attribute of a dataTable tag references the data to be included in the table. The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable. In the dataTable tag from the List.jsp page, the value attribute points to a list of catalog items. The var attribute points to a single item in that list. As the UIData component iterates through the list, each reference to dataTableItem points to the current item in the list.
  • getItems() method wraps a List of items, returned from the CatalogFacade Stateless Session EJB, in a DataModel. dataTable, supports data binding to a collection of data objects represented by a DataModel instance, which is the current value of this component itself. The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a row index. The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the data that corresponds to the current row index.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • note the taglib declaration. JSF comes with its own set of JSP custom tag libraries. Here we declare two JSF tag libraries, html and core. The html JSF tag library contains HTML rendering tags while the core JSF tag library contains JSF core tags. These libraries expose most of the JSF components, validators, event registers, and so on. Note that there are several UI components in this page. And they are <h:output_text>, <h:inputText>, <h:commandButton>. The <h:output_text>elements contains value attributes whose values come from the property values of a JavaBean called UserNumberBean. The names of these properties of this bean are called minimum and maximum. The <h:inputText> element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The <h:commandButton> displays a button that can be pressed for submitting the form data. ·form tag represents an input form with which the user can submit data to the server.
  • At the invoke application phase– the JSF controller invokes the application to handle Form submissions. The component values will have been converted, validated, and applied to the model objects, so you can now use them to execute the application's business logic. At this phase, you also get to specify the next logical view for a given sequence or number of possible sequences. You do this by defining a specific outcome for a successful form submission and returning that outcome. For example: on successful outcome, move the user to the next page. For this navigation to work, you will have to create a mapping to the successful outcome as a navigation rule in the faces-config.xml file. Once the navigation occurs, you move to the final phase of the lifecycle.
  • note the taglib declaration. JSF comes with its own set of JSP custom tag libraries. Here we declare two JSF tag libraries, html and core. The html JSF tag library contains HTML rendering tags while the core JSF tag library contains JSF core tags. These libraries expose most of the JSF components, validators, event registers, and so on. Note that there are several UI components in this page. And they are <h:output_text>, <h:inputText>, <h:commandButton>. The <h:output_text>elements contains value attributes whose values come from the property values of a JavaBean called UserNumberBean. The names of these properties of this bean are called minimum and maximum. The <h:inputText> element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The <h:commandButton> displays a button that can be pressed for submitting the form data. ·form tag represents an input form with which the user can submit data to the server.
  • At the invoke application phase– the JSF controller invokes the application to handle Form submissions. The component values will have been converted, validated, and applied to the model objects, so you can now use them to execute the application's business logic. At this phase, you also get to specify the next logical view for a given sequence or number of possible sequences. You do this by defining a specific outcome for a successful form submission and returning that outcome. For example: on successful outcome, move the user to the next page. For this navigation to work, you will have to create a mapping to the successful outcome as a navigation rule in the faces-config.xml file. Once the navigation occurs, you move to the final phase of the lifecycle.
  • At the invoke application phase– the JSF controller invokes the application to handle Form submissions. The component values will have been converted, validated, and applied to the model objects, so you can now use them to execute the application's business logic. At this phase, you also get to specify the next logical view for a given sequence or number of possible sequences. You do this by defining a specific outcome for a successful form submission and returning that outcome. For example: on successful outcome, move the user to the next page. For this navigation to work, you will have to create a mapping to the successful outcome as a navigation rule in the faces-config.xml file. Once the navigation occurs, you move to the final phase of the lifecycle.
  • note the taglib declaration. JSF comes with its own set of JSP custom tag libraries. Here we declare two JSF tag libraries, html and core. The html JSF tag library contains HTML rendering tags while the core JSF tag library contains JSF core tags. These libraries expose most of the JSF components, validators, event registers, and so on. Note that there are several UI components in this page. And they are <h:output_text>, <h:inputText>, <h:commandButton>. The <h:output_text>elements contains value attributes whose values come from the property values of a JavaBean called UserNumberBean. The names of these properties of this bean are called minimum and maximum. The <h:inputText> element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The <h:commandButton> displays a button that can be pressed for submitting the form data. ·form tag represents an input form with which the user can submit data to the server.
  • Glass fish is an open source reference implementation of Java EE. All of the pieces like JSF , EJB are part of Glassfish. The Sun application server is based on Glassfish.
  • Mainly to show Open Source contributions from Sun. We're not rookies in server-side Open Source Java! :) Also interesting to show the progression: v1 was all about Java EE 5 v2 is all about enterprise features v3 is all about modularization and changing the game to leapfrog the competition in an even bigger way
  • Spring is one of the driving forces behind popularizing the POJO programming model and dependency injection. With Spring, you simply inject collaborating objects called dependencies using JavaBeans properties and configuration files. The ability to inject collaborating objects is often called IoC (inversion of control). Or dependency injection AOP allows developers to create non-domain concerns, called crosscutting concerns, and insert them in their application code. With AOP, common services like logging, persistence, transactions, and the like can be factored into aspects and applied to domain objects without complicating the object model of the domain objects. The IoC capabilities allowing injection of dependent objects is a great mechanism for testing your code. It is easy now to inject mock objects (object for testing), and test your classes in an isolated manner. Many developers want to choose a persistence, web, or messaging framework without having to do the integration work. The developers of the Spring framework realized that no matter which persistence, web, messaging, or "whatever" framework they selected to support, someone would want to use something else, and a better alternative would eventually come along. Also, this type of integration is typically expensive. By following the IoC and SoC principles, Spring was able to be both lightweight enough to let developers decide how much of the framework they needed, and flexible enough to support many permutations of competing component frameworks.
  • Spring provides several modules, such as the following: AOP module JDBC abstraction and DAO module ORM integration module Web module MVC framework provides a scaffolding for services you can pick and choose pieces of it Spring also includes patterns and recipes spring provides a simple programming model for using resources such as JDBC or JMS or using popular persistence frameworks like Hibernate or TopLink by abstracting low-level API and configuration from developers without limiting developers' choices. Spring AOP supports method interception. Key AOP concepts supported include: Interception: Custom behavior can be inserted before or after method invocations against any interface or class. This equates to “before”, “after” and "around advice" in AspectJ terminology. Introduction: Specifying that an advice should cause an object to implement additional interfaces. This can amount to mixin inheritance. Static and dynamic pointcuts: Specifying the points in program execution at which interception should take place. Static pointcuts concern method signatures; dynamic pointcuts may also consider method arguments at the point where they are evaluated. Pointcuts can be reused.
  • Spring does not reinvent the wheel. Thus you'll find no logging packages in Spring, no connection pools, no distributed transaction coordinator. All these things are provided by open source projects (such as Commons Logging, which we use for all our log output, or Commons DBCP), or by your application server or web container. For the same reason, we don't provide an O/R mapping layer. There are good solutions to this problem such as TopLink, Hibernate, JPA and JDO. Spring is not positioned as an alternative to Java EE but as a framework that facilitates the development of applications with Java EE. That's one of the primary reasons for Spring being successful as a framework. You can use the Spring framework on its own or inside a Java EE container.
  • The basic concept here is the BeanFactory , which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic A Spring bean factory is a generic factory that enables configured objects to be retrieved by name, and which can manage relationships between objects. Spring uses IoC as a basic concept throughout a full-featured framework. with Dependency Injection the container figures out that the component needs an X object, and provides it to it at runtime. The container does this figuring out based on method signatures (usually JavaBean properties or constructors) and, configuration data such as XML.
  • The two major flavors of Dependency Injection are Setter Injection (injection via JavaBean setters); and Constructor Injection (injection via constructor arguments). Spring provides sophisticated support for both, and even allows you to mix the two when configuring the one object. The root of a Spring XML bean definition document is a <beans> element. The <beans> element contains one or more <bean> definitions. normally specify the class and properties of each bean definition.and also specify the id, which will be the name that we'll use this bean with in our code. Relationships between beans are specified using a combination of the property and "ref" attribute
  • Spring also provides two kinds of what we call "autowire" support, where it figures out the dependencies between beans: autowire by type, and autowire by name Autowire support has the advantage of reducing the volume of configuration. Since Spring 2.5, you can use annotations to configure your beans. By simply including a <context:annotation-config/> element in your application context's configuration, you can use these annotations not only on your property setter methods, but also on constructors, fields, and arbitrary methods and method parameters. Here's an example using Spring's @Autowired annotation to configure the itemcontroller bean that depends on the catalogservice
  • Spring 2.5 allows autowiring by name to be used for constructors via the @Qualifier parameter annotation. you can make use of Spring's support for classpath scanning as a means to identify candidate beans. Spring provides @Component and @Repository "stereotyping" annotations that you can place on your candidate bean classes. By using the <context:component-scan base-package="…"> configuration element, you tell Spring to automatically scan for and load as beans those classes in a given base package or its subpackages. This way, you won't have to declare each bean in your configuration – they will automatically be detected.
  • getItems() method wraps a List of items, returned from the CatalogFacade Stateless Session EJB, in a DataModel. dataTable, supports data binding to a collection of data objects represented by a DataModel instance, which is the current value of this component itself. The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a row index. The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the data that corresponds to the current row index.
  • The recommended way to integrate Spring with JSF is to configure the Spring DelegatingVariableResolver in the faces-context.xml. The <application> <variable-resolver> elements in a faces-config.xml file allows a Faces-based application to register a custom replacement class for the implementation of the standard Faces VariableResolver implementation. The Spring DelegatingVariableResolver first delegates to the original resolver of the underlying JSF implementation, then to the Spring root WebApplicationContext. This allows you to configure Spring Beans as managed properties of your JSF Managed Beans. For example, below the catalogService Spring Bean is configured as a managed property of the ItemController JSF ManagedBean:
  • The recommended way to integrate Spring with JSF is to configure the Spring DelegatingVariableResolver in the faces-context.xml. The <application> <variable-resolver> elements in a faces-config.xml file allows a Faces-based application to register a custom replacement class for the implementation of the standard Faces VariableResolver implementation. The Spring DelegatingVariableResolver first delegates to the original resolver of the underlying JSF implementation, then to the Spring root WebApplicationContext. This allows you to configure Spring Beans as managed properties of your JSF Managed Beans. For example, below the catalogService Spring Bean is configured as a managed property of the ItemController JSF ManagedBean:
  • IJavaServer Faces UI components are configurable, reusable elements that
  • @Repository – Indicates that a class functions as a repository or a data access object (DAO) @Transactional – Provides annotation driven demarcation for transactions
  • # The class must be annotated with the javax.persistence.Entity annotation. # The class must have a public no-argument constructor. .# If an entity instance is to be passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the Serializable interface. # Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
  • TopLink JPA supports lazy loading using load-time weaving of the entity classes. When functioning within an EJB 3.0 container, weaving happens transparently. However, when using TopLink JPA outside of a container, it is up to you to enable this functionality <bean class=”... GlassFishLoadTimeWeaver ”/>
  • Glass fish is an open source reference implementation of Java EE. All of the pieces like JSF , EJB are part of Glassfish. The Sun application server is based on Glassfish.
  • Spring Pros: Inversion of Control makes it easy to test Cons: Configuration intensive - lots of XML, easier now even though EJB 3 is a specification and Spring is a framework, you can use them together successfully to build flexible, powerful applications. You can use parts of the EJB 3 implementation, or all of it, within your Spring applications. Spring can simplify the use of both EJB 3 and JPA, but at the price of foraging through Spring's XML configuration files. EJB 3 is a great framework for building enterprise Java applications, and it significantly improves developer productivity. It has some minor limitations, such as support for POJO injection, these limitations will be addressed in webbeans.
  • Web Beans has been submitted as JSR-299 with support from JBoss, The purpose of this specification is to unify the JSF managed bean component model with the EJB component model, resulting in a significantly simplified programming model for web-based applications.
  • The @Name annotation binds the component to a contextual variable its just like <manage-bean-name> in the JSF XML Every component has a name When name is first requested, instance is created Several ways to get access to a component by name Value expression - #{beerAction} Annotation - @In("beerAction") Context=Buckets where the component instances are stored Stored in request scope by default Request scope == event context Seam introduces the conversation context Supports a single use-case, which may span multiple pages and actions
  • The @Name annotation binds the component to a contextual variable its just like <manage-bean-name> in the JSF XML Every component has a name When name is first requested, instance is created Several ways to get access to a component by name Value expression - #{beerAction} Annotation - @In("beerAction") Context=Buckets where the component instances are stored Stored in request scope by default Request scope == event context Seam introduces the conversation context Supports a single use-case, which may span multiple pages and actions
  • Similar to dependency injection container satisfies the needs of components Bijection occurs on every method invocation Prefix "bi" implies that it occurs twice injection is applied before the method is invoked outjection is applied after the method is invoked Bijection = Injection + Outjection
  • The @Name seam annotation specifies the (application unique) component name item, which is used in the Detail.jsp to display the selected item's attributes. The @Scope Seam annotation binds the item instance to the org.jboss.seam.ScopeType.EVENT context. APPLICATION BUSINESS_PROCESS The business process context. CONVERSATION The conversation context. EVENT The event (request) context. METHOD The method context. PAGE The page context. SESSION
  • The recommended way to integrate Spring with JSF is to configure the Spring DelegatingVariableResolver in the faces-context.xml. The <application> <variable-resolver> elements in a faces-config.xml file allows a Faces-based application to register a custom replacement class for the implementation of the standard Faces VariableResolver implementation. The Spring DelegatingVariableResolver first delegates to the original resolver of the underlying JSF implementation, then to the Spring root WebApplicationContext. This allows you to configure Spring Beans as managed properties of your JSF Managed Beans. For example, below the catalogService Spring Bean is configured as a managed property of the ItemController JSF ManagedBean:
  • The value attribute of a dataTable tag references the data to be included in the table. The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable. In the dataTable tag from the List.jsp page, the value attribute points to a list of catalog items. The var attribute points to a single item in that list. As the UIData component iterates through the list, each reference to dataTableItem points to the current item in the list.
  • When the List.jsp page is diplayed it will try to resolve the items context variable. Since this context variable is not initialized, Seam will call the factory method getItems(), The @DataModel Seam annotation exposes an attribute of type java.util.List to a JSF page as an instance of javax.faces.model.DataModel. The <h:dataTable> supports data binding to a collection of data objects represented by a DataModel instance. The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a row index. The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the data that corresponds to the current row index. In this case, the DataModel is made available in a session context variable named items.
  • The @Interceptors EJB 3.0 annotation registers the SeamInterceptor.class as an EJB interceptor for this session bean component. The Seam framework uses EJB interceptors to perform bijection, context demarcation, validation, etc, (the interceptor could be defined in the ejb-jar.xml instead).
  • The value attribute of a dataTable tag references the data to be included in the table. The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable. In the dataTable tag from the List.jsp page, the value attribute points to a list of catalog items. The var attribute points to a single item in that list. As the UIData component iterates through the list, each reference to dataTableItem points to the current item in the list.
  • The @DataModelSelection Seam annotation tells Seam to inject the DataModel List element corresponding to the clicked link into the item attribute. @Out Seam annotation transfers the value of this attribute to the item event context variable, making it available to a JSP page
  • Seam Pros • Fully integrated Java EE 5 based web application framework • By means of Seam-Gen, very quick generation of applications • Simplification of an EJB3 and JSF development to the effect that no more glue code is required • Many cool features, which considerably simplify the development of applications (pre-actions, request parameters, conversation scope, ...) Now the cons: • No layers any more, good or bad • The abolition of the strict division into layers is a matter of opinion. • Mixture of GUI and persistence layer • Not yet standardized
  • Seam unifies JavaServer Faces, Enterprise JavaBeans 3, the Java Persistence API, under an accessible component-based model, empowering you to create stateful enterprise applications with tremendous agility. Still, Spring sports many features that you won't find in Seam. It's likely that these features -- such as lightweight remoting, advanced aspect-oriented programming (AOP) declarations, framework template classes, and emulated container resource injections, to mention a few -- simply aren't the passion of Seam.
  • JavaEE Spring Seam

    1. 1. JavaEE with Spring or Seam Carol McDonald, Java Architect
    2. 2. About the Speaker <ul><li>Carol cDonald: </li></ul><ul><ul><li>Java Architect at Sun Microsystems </li></ul></ul><ul><ul><li>Before Sun, worked on software development of: </li></ul></ul><ul><ul><ul><li>Application to manage car Loans for Toyota (>10 million loans) </li></ul></ul></ul><ul><ul><ul><li>Pharmaceutical Intranet apps ( Roche Switzerland) </li></ul></ul></ul><ul><ul><ul><li>Telecom Network Mgmt app ( Digital France) </li></ul></ul></ul><ul><ul><ul><li>X.400 Email Server ( IBM Germany) </li></ul></ul></ul>
    3. 3. Agenda <ul><li>Look at a sample application built 3 ways: </li></ul><ul><li>using Java EE, </li></ul><ul><li>Java EE and Spring, </li></ul><ul><li>Java EE and Seam </li></ul><ul><li>all running on Glassfish </li></ul>
    4. 4. Sample Application
    5. 5. Catalog Java EE Application <ul><ul><ul><li>Persistence – JPA Entities </li></ul></ul></ul>DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
    6. 6. JPA Unifying/Standardizing Persistence <ul><li>Based on existing successful technologies: </li></ul><ul><ul><li>TopLink, Hibernate, Kodo, Java Data Object s, etc. </li></ul></ul><ul><ul><li>One common API for all major ORM frameworks </li></ul></ul><ul><ul><li>Standardized annotations @ and XML </li></ul></ul><ul><ul><ul><li>xml for mapping is optional </li></ul></ul></ul><ul><ul><li>Support for pluggable 3 rd party Persistence provider s </li></ul></ul>
    7. 7. JPA: Simplifying/Unifying/Standardizing Persistence <ul><li>POJO based programming/persistence model </li></ul><ul><ul><li>Simple Java classes – not EJB components </li></ul></ul><ul><ul><ul><li>Can be used in Java SE , web or EJB -based applications </li></ul></ul></ul><ul><ul><ul><li>No need for D ata T ransfer O bjects </li></ul></ul></ul><ul><ul><ul><li>Facilitates testability </li></ul></ul></ul><ul><li>Simpler and easier: </li></ul><ul><ul><li>Most configuration is defaulted – configure by exception only (configure only to override default) </li></ul></ul>
    8. 8. Entity Annotated as “Entity” @Id denotes primary key Getters/setters to access state @Entity public class Item implements Serializable { @Id protected Long id; private String name; private BigDecimal price; public Item() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getPrice() {return price;} public void setPrice( BigDecimal name){this.price=price;} … }
    9. 9. Simple Mapping Mapping defaults to matching column name . Only configure if entity field and table column names are different public class Item { int id; String name; String description; String url ; } @Entity @Column(name=“DESC”) @Id Item ID NAME DESC URL
    10. 10. Relationships JPA Standardized O/R Mapping <ul><li>Standardized o bject/ r elational m apping </li></ul><ul><ul><li>annotations to specify how to map attributes to DB </li></ul></ul><ul><ul><ul><li>xml for mapping is optional </li></ul></ul></ul><ul><ul><li>Most configuration is defaulted </li></ul></ul>Relationships
    11. 11. Relationship Mappings – OneToMany Bidirectional public class Product { int id; ... Collection<Item> items; } public class Item { int id; ... Product product; } @Entity @Entity @OneToMany( mappedBy =“ product ”) @ManyToOne @Id @Id 1 n has to say where the foreign key is using mappedBy Item ID PROD_ID PRODUCT ID . . .
    12. 12. Persistence Context EntityManager persist() remove() refresh() merge() find() createQuery() createNamedQuery() contains() flush() EntityManager API to manipulate entities Set of managed entities Interface thru which applications interact with the entities and the persistence engine Servlets EJBs Java app
    13. 13. How Does it Work? Entity Manager <ul><li>EntityManager API to manipulate entities </li></ul><ul><li>stores/retrieves entities in DB: </li></ul><ul><ul><li>Use EntityManager methods to persist, update, delete data </li></ul></ul><ul><ul><ul><li>em. persist (p); em. merge (p); em. find (p.class, id); ; em. remove (p); </li></ul></ul></ul><ul><ul><li>Query using EJB QL or SQL </li></ul></ul><ul><ul><ul><li>List<Passenger> listP = em. createQuery (“select p from Passenger p”) .getResultList (); </li></ul></ul></ul>
    14. 14. Persistence Context <ul><li>~HashMap of Managed Entity objects </li></ul><ul><ul><li>first-level cache </li></ul></ul><ul><ul><li>holds (at most) one in-memory Entity for each database row </li></ul></ul><ul><ul><li>can do dirty checking of objects and write SQL as late as possible (automatic or manual flushing) </li></ul></ul><ul><li>The Persistence Context has a scope, for EJBs: </li></ul><ul><ul><li>default : same scope as the system transaction (JTA) </li></ul></ul><ul><ul><li>extended : the PC is bound to a stateful session bean </li></ul></ul>
    15. 15. Declarative Transaction Management Example TX_REQUIRED TX_REQUIRED TX_REQUIRED PC PC PC Session Facade Inventory Service Order Service Check Out 1. Update Inventory New Persistence Context Persistence Context Propagated Transaction Attributes 2. Create Order
    16. 16. Persistence Context- Transactional vs. Extended @Stateless public class OrderSessionStateless implements OrderService { @PersistenceContext(unitName=”java_one”) EntityManager em; public void addLineItem (OrderLineItem li){ // First, look up the order. Order order = em.find(Order.class, orderID); order.lineItems.add(li); } @Stateful public class OrderSessionStateful implements OrderService { @PersistenceContext(type = PersistenceContextType. EXTENDED )) EntityManager em; // Order is a member variable Loaded from the db in lookupOrder Order order public void addLineItem (OrderLineItem li){ // No em.find invoked for the order object order.lineItems.add(li); }
    17. 17. Catalog Java EE Application <ul><ul><ul><li>Stateless Session EJB </li></ul></ul></ul>DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
    18. 18. Business Interface <ul><li>public interface CatalogService { </li></ul><ul><li>public Item getItem(String itemID); </li></ul><ul><li>public int getItemCount(); </li></ul><ul><li>public List<Item> getItems (int firstItem, </li></ul><ul><ul><ul><ul><li>int batchSize ); </li></ul></ul></ul></ul><ul><li>} </li></ul>CatalogService Business Interface
    19. 19. Catalog Stateless Session EJB, JPA Query @Stateless public class Catalog implements CatalogService { @PersistenceContext(unitName=”PetCatalogPu”) EntityManager em; @TransactionAttribute(NOT_SUPPORTED) public List<Item> getItems (int firstItem , int batchSize ) { Query q = em . createQuery (&quot; select i from Item as i &quot;); q. setMaxResults ( batchSize ); q. setFirstResult ( firstItem ); List<Item> items= q.getResultList(); return items; } }
    20. 20. Java EE: Dependency Injection <ul><li>Dependency Injection = Inversion of Control </li></ul><ul><li>Don't call us, we'll call you (Hollywood Principle) </li></ul><ul><ul><li>Bean specifies what it needs through @ </li></ul></ul><ul><li>References to resources are injected when instance is constructed: </li></ul><ul><ul><li>@Resource : for connection factories, EJBContext, UserTransaction , etc. </li></ul></ul><ul><ul><li>@EJB : For EJB References </li></ul></ul><ul><ul><li>@PersistenceContext : For container-managed EntityManager </li></ul></ul><ul><ul><li>@PersistenceUnit : For EntityManagerFactory </li></ul></ul>
    21. 21. Agenda <ul><li>Catalog Java EE Application </li></ul><ul><ul><li>JSF </li></ul></ul>
    22. 22. JSF Component, Event Driven Web Framework <ul><li>Pages composed of server side components </li></ul>View Root Form id=guess Managed Bean getUserNumber() setUserNumber(..) guess() Business Service guess() <ul><ul><li>Events call ManagedBean methods </li></ul></ul>UIIput id=guessNum UICommand id=submit
    23. 23. What is a JSF UI Component? Some Standard Components
    24. 24. Some Open Source UI Components
    25. 25. UI Components <ul><ul><li>So... what is a UI component? </li></ul></ul><ul><ul><ul><li>To a page author – XML tag (JSP or Facelets) </li></ul></ul></ul><ul><ul><ul><li>To a component author – component class and renderer </li></ul></ul></ul>maintains component state, processes input renders a user interface Component Class XML Tag Renderer
    26. 26. JSF Web Framework View Controller Model Request Service Interface Events
    27. 27. Catalog Java EE Application <ul><ul><ul><li>JSF components and Managed Bean </li></ul></ul></ul>DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
    28. 28. List Items page Data Table
    29. 29. list.jsp <ul><li><h:dataTable value='#{ item.items }' var=' dataTableItem ' > </li></ul><ul><li><h:column> </li></ul><ul><li><f:facet name=&quot;header&quot;> </li></ul><ul><li>h: outputText value=&quot;Name&quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li><h:commandLink action =&quot;#{ item.detailSetup }&quot; value =&quot;#{ dataTableItem.name }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li><h:column> </li></ul><ul><li><f: facet name=&quot; header &quot;> </li></ul><ul><li>h: outputText value =&quot; Photo &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li>< h: graphicImage url =&quot;#{ dataTableItem.imagethumburl }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li><h:column> </li></ul><ul><li><f:facet name=&quot;header&quot;> </li></ul><ul><li>h: outputText value =&quot; Price &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li><h: outputText value =&quot;#{ dataTableItem . price }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li></h:dataTable> </li></ul>
    30. 30. Binding UI to Managed Bean <ul><li>list.jsp </li></ul><ul><ul><li><h: dataTable </li></ul></ul><ul><ul><li>value =&quot;#{ itemController .items }&quot; </li></ul></ul><ul><li>faces-config.xml </li></ul><ul><li><managed-bean> </li></ul><ul><li>< managed-bean-name > </li></ul><ul><li>itemController </li></ul><ul><ul><li></managed-bean-class> </li></ul></ul><ul><li>< managed-bean-class > </li></ul><ul><li>package. ItemController </li></ul><ul><li></managed-bean-class> </li></ul><ul><ul><li><managed-bean-scope> </li></ul></ul><ul><ul><li>session </li></ul></ul><ul><ul><li></managed-bean-scope> </li></ul></ul><ul><ul><li></managed-bean> </li></ul></ul>ItemController.java public class ItemController ... public long getItems() { <ul><ul><li>JSP, JSF </li></ul></ul><ul><ul><li>Expression </li></ul></ul><ul><ul><li>Language </li></ul></ul>Managed Bean property
    31. 31. Managed Bean Value Binding <ul><li>UI Output component value attribute : </li></ul><ul><ul><li>The property getter is invoked when the component is rendered </li></ul></ul><ul><ul><li><h: dataTable value =&quot;#{ itemController .items }&quot;/> </li></ul></ul><ul><ul><li>The property setter is invoked when the component input is processed </li></ul></ul><ul><ul><li><h: input Text value =&quot;#{ user .name }&quot;/> </li></ul></ul>GET SET
    32. 32. list.jsp Page < h:dataTable value='#{ itemController.items }' var=' dataTableItem '> <h:column> <f:facet name='header'> <h:outputText> value='Name'/> </f:facet> < h:commandLink action='#{item.detailSetup}' value='#{ dataTableItem .name}'/> </h:column> <h:column> ... < h:graphicImage url='#{ dataTableItem .imagethumburl}'/> ... < h:outputText value='#{ dataTableItem .price}'/> ... </h:dataTable>
    33. 33. UIComponents Binding to a Managed Bean <ul><li>public class ItemController { </li></ul><ul><li>private DataModel model ; </li></ul><ul><li>DataModel getItems(){ </li></ul><ul><li>. . . </li></ul><ul><li>return model; </li></ul><ul><li>} </li></ul><ul><li>. . . </li></ul><ul><li>} </li></ul><ul><ul><li><h: dataTable value =&quot;#{ itemController .items }&quot; </li></ul></ul>Managed Bean property Managed Bean <ul><ul><li>dataTable </li></ul></ul><ul><li>useful to show a Collection in a table </li></ul><ul><li>binding to DataModel which wraps </li></ul><ul><li>a collection of data objects </li></ul>Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page
    34. 34. Managed Bean: ItemController <ul><li>import javax.faces.model.DataModel ; </li></ul><ul><li>import javax.faces.model.ListDataModel; </li></ul><ul><li>public class ItemController { </li></ul><ul><li>private DataModel model; </li></ul><ul><li>private int batchSize = 10; </li></ul><ul><li>private int firstItem = 0; </li></ul><ul><li>@EJB private CatalogService catalog ; </li></ul><ul><li>public DataModel getItems() { </li></ul><ul><li>model = new ListDataModel ( </li></ul><ul><ul><ul><li>catalog.getItems( firstItem,batchSize) ; </li></ul></ul></ul><ul><li>return model; </li></ul><ul><li>} </li></ul><ul><li>. . . </li></ul><ul><ul><li>dataTable binds to a DataModel </li></ul></ul><ul><li>which wraps Collection of data objects </li></ul>
    35. 35. Catalog Stateless Session EJB @Stateless public class Catalog implements CatalogService { @PersistenceContext(unitName=”PetCatalogPu”) EntityManager entityManager; @TransactionAttribute(NOT_SUPPORTED) public List<Item> getItems (int firstItem, int batchSize) { Query q = em. createQuery (&quot; select i from Item as i &quot;); q. setMaxResults (batchSize); q. setFirstResult (firstItem); List<Item> items= q.getResultList(); return items; } }
    36. 36. Relationship Between Objects getItems() via EntityBean 1 m #{itemController.items} Item Entity Product Entity Catalog StatelessSB Item Controller list.jsp
    37. 37. List Items page Link to see Item Details JSF is event-driven, listens for actions
    38. 38. list.jsp <ul><li><h:dataTable value='#{ itemController.items }' var =' dataTableItem '> </li></ul><ul><li><h:column> </li></ul><ul><li><f:facet name=&quot;header&quot;> </li></ul><ul><li>h: outputText value=&quot; Name &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li><h: commandLink action =&quot;#{ itemController.detailSetup }&quot; </li></ul><ul><li>value =&quot;#{ dataTableItem.name }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li><h:column> </li></ul><ul><li><f: facet name=&quot; header &quot;> </li></ul><ul><li>h: outputText value =&quot; Photo &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li>< h: graphicImage url =&quot;#{ dataTableItem.imagethumburl }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li><h:column> </li></ul><ul><li><f:facet name=&quot;header&quot;> </li></ul><ul><li>h: outputText value =&quot; Price &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li><h: outputText value =&quot;#{ dataTableItem.price }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li></h:dataTable> </li></ul>Click causes Action Event JSF is event-driven, listens for actions
    39. 39. <ul><ul><li>JSF controller handles action events, such as submitting a form or linking to another page. </li></ul></ul>JSF Standard request processing lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations <ul><ul><li>action events </li></ul></ul>JSF is event-driven, listens for actions
    40. 40. JSF Actions <ul><ul><li>Command Action : Refers to a backing bean method that performs navigation processing and returns a logical outcome String </li></ul></ul><ul><li><h: commandLink action =&quot;#{ itemController.detailSetup } &quot; ... /> </li></ul><ul><li>public class ItemController { </li></ul><ul><li>private Item item ; </li></ul><ul><li>private DataModel model ; </li></ul><ul><li>public Item getItem() { </li></ul><ul><li>return item; </li></ul><ul><li>} </li></ul><ul><li>public String detailSetup() { </li></ul><ul><li>item = (Item) model.getRowData(); </li></ul><ul><li>return &quot; item_detail &quot;; </li></ul><ul><li>} </li></ul>
    41. 41. Navigation Example from-view to-view from-outcome list.jsp new_usr.jsp error.jsp error.jsp detail.jsp “ item_detail” new user error
    42. 42. Navigation <ul><li><navigation-rule> </li></ul><ul><ul><li>< from-view -id> /list.jsp </from-tree-id> </li></ul></ul><ul><ul><li><navigation-case> </li></ul></ul><ul><ul><li>< from-outcome > item_detail </from-outcome> </li></ul></ul><ul><ul><li>< to-view -id> /detail.jsp </to-tree-id> </li></ul></ul><ul><ul><li></navigation-case> </li></ul></ul><ul><ul><li>. . . </li></ul></ul><ul><ul><li></navigation-rule> </li></ul></ul>< h: commandLink action =&quot;#{ itemController.detailSetup } />
    43. 43. Standard request processing lifecycle JavaServer Faces Lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations
    44. 44. Item Detail Page
    45. 45. detail.jsp <ul><li>. . . </li></ul><ul><li><h:panelGrid columns=&quot;2&quot;> </li></ul><ul><li><h: outputText value=&quot; Name: &quot;/> </li></ul><ul><li><h: outputText value=&quot;#{ itemController.item.name }&quot; title=&quot;Name&quot; /> </li></ul><ul><li><h: outputText value=&quot;Description:&quot;/> </li></ul><ul><li><h:outputText value=&quot;#{ itemController.item.description }&quot; title=&quot;Description&quot; /> </li></ul><ul><li><h:outputText value=&quot;Photo:&quot;/> </li></ul><ul><li><h: graphicImage url=&quot;#{ itemController.item.imageurl }&quot; title=&quot;Imageurl”/> </li></ul><ul><li><h:outputText value=&quot;Price:&quot;/> </li></ul><ul><li><h:outputText value=&quot;#{ itemController.item.price }&quot; title=&quot;Price&quot; /> </li></ul><ul><li><h:outputText value=&quot;City:&quot;/> </li></ul><ul><li><h:outputText value=&quot;#{ itemController.item.address.city }&quot; title=&quot;Address&quot; /> </li></ul><ul><li><h:outputText value=&quot;Seller email:&quot;/> </li></ul><ul><li><h:outputText value=&quot;#{ itemController.item.contactinfo.email }&quot; title=&quot;Address&quot; </li></ul><ul><li></h:panelGrid> </li></ul><ul><li><h: commandLink action=&quot;item_list&quot; value=&quot;List of Items&quot;/> </li></ul>Calls itemController.getItem().getName()
    46. 46. UIOutput component value attribute <ul><li><h: outputText value=&quot;#{ itemController.item.name }&quot; title=&quot;Name&quot; /> </li></ul><ul><li>public class ItemController { </li></ul><ul><li>private Item item ; </li></ul><ul><li>private DataModel model ; </li></ul><ul><li>public Item getItem() { </li></ul><ul><li>return item; </li></ul><ul><li>} </li></ul><ul><li>public String detailSetup() { </li></ul><ul><li>item = (Item) model.getRowData(); </li></ul><ul><li>return &quot; item_detail &quot;; </li></ul><ul><li>} </li></ul>Calls itemController.getItem().getName()
    47. 47. Get Next List of Items page
    48. 48. Invoke Application Phase <ul><ul><li>UICommand Action : Refers to a backing bean method that performs navigation processing and returns a logical outcome String </li></ul></ul><ul><li><h: commandLink action =&quot;#{ itemController.next } &quot; ... /> </li></ul><ul><li>public class ItemController { </li></ul><ul><li>public String next() { </li></ul><ul><li>if (firstItem + batchSize < itemCount) { </li></ul><ul><li>firstItem += batchSize; </li></ul><ul><li>} </li></ul><ul><li>return &quot; item_list &quot;; </li></ul><ul><li>} </li></ul>
    49. 49. Navigation <ul><li><navigation-rule> </li></ul><ul><ul><li><navigation-case> </li></ul></ul><ul><ul><li>< from-outcome > item_list </from-outcome> </li></ul></ul><ul><ul><li>< to-view -id> /list.jsp </to-tree-id> </li></ul></ul><ul><ul><li></navigation-case> </li></ul></ul><ul><ul><li>. . . </li></ul></ul><ul><ul><li></navigation-rule> </li></ul></ul>< h: commandLink action =&quot;#{ itemController.next } />
    50. 50. Standard request processing lifecycle JavaServer Faces Lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations
    51. 51. <ul><li><h:dataTable value='#{ itemController.items }' var =' dataTableItem ' border=&quot;1&quot; > </li></ul><ul><li><h:column> </li></ul><ul><li><f:facet name=&quot;header&quot;> </li></ul><ul><li>h: outputText value=&quot; Name &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li><h: commandLink action =&quot;#{ item.detailSetup }&quot; value =&quot;#{ dataTableItem .name }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li><h:column> </li></ul><ul><li><f: facet name=&quot; header &quot;> </li></ul><ul><li>h: outputText value =&quot; Photo &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li>< h: graphicImage url =&quot;#{ dataTableItem .imagethumburl }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li><h:column> </li></ul><ul><li><f:facet name=&quot;header&quot;> </li></ul><ul><li>h: outputText value =&quot; Price &quot;/> </li></ul><ul><li></f:facet> </li></ul><ul><li><h: outputText value =&quot;#{ dataTableItem .price }&quot;/> </li></ul><ul><li></h:column> </li></ul><ul><li></h:dataTable> </li></ul>Render Will call getItems() which will display next items
    52. 52. GlassFish Application Server <ul><li>Java EE 5 , Toplink JPA </li></ul><ul><li>Enterprise Quality </li></ul><ul><ul><li>GlassFish Enterprise </li></ul></ul><ul><li>Open Source </li></ul><ul><ul><li>Dual-licensed with GPLv2/CPE </li></ul></ul><ul><li>Community at Java.Net </li></ul><ul><ul><li>Sources, bug DBs, discussions at Java.Net </li></ul></ul><ul><ul><li>Roadmaps, Architecture Documents </li></ul></ul><ul><li>Sample application on Carol's blog : </li></ul><ul><li>http://weblogs.java.net/blog/caroljmcdonald/ </li></ul>
    53. 53. Timeline of Project GlassFish Tomcat Jasper Catalina JSTL Struts Crimson XSLTC Xalan Xerces JAXB JAX-RPC JSF June 2005 May 2006 GlassFish Launch v2 v1 v3 Mid-2009 UR1 v2.1 UR2 v3 Prelude Oct 2008 Dec 2008 Sept. 2007
    54. 54. Demo Demo Netbeans 6.5 JPA entity JSF pages generation from DB tables
    55. 55. Agenda <ul><li>Catalog Java EE Application </li></ul><ul><li>Catalog Spring 2.5 JSF and JPA Application </li></ul><ul><li>Catalog Java EE Seam Application </li></ul><ul><li>Summary </li></ul>
    56. 56. Spring Framework Goals <ul><li>Inversion of control container for application components and lifecycle </li></ul><ul><ul><ul><li>Wiring components through Dependency Injection </li></ul></ul></ul><ul><ul><ul><li>Promotes de-coupling among the parts that make up an application </li></ul></ul></ul><ul><li>Provide Java AOP implementation </li></ul><ul><ul><li>allowing the separation of cross-cutting concerns </li></ul></ul><ul><ul><ul><li>Logging ... </li></ul></ul></ul><ul><li>Facilitate unit testing </li></ul><ul><ul><li>Allow effective TDD </li></ul></ul><ul><ul><li>Allow POJO classes to be unit tested outside the container </li></ul></ul>
    57. 57. Spring Framework
    58. 58. What Is Spring Not? <ul><li>Not Java EE Platform Container </li></ul><ul><ul><li>Spring typically runs within a Java EE platform or Web container </li></ul></ul><ul><ul><li>Spring can run in Java SE or Java EE </li></ul></ul><ul><ul><li>Spring leverages and prefers to use existing standards </li></ul></ul><ul><ul><li>relies upon the services of the server in which it is deployed </li></ul></ul>
    59. 59. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
    60. 60. Bean Factory and Dependency Injection Spring Bean Factory injects dependencies Application's POJOs Configuration file Dependencies in applicationContext.xml Fully configured and ready to use objects
    61. 61. Spring Dependency Injection <ul><li>public class ItemController { </li></ul><ul><li>private CatalogService catalogService ; </li></ul><ul><li>public void setCatalogService (CatalogService catalogService) { </li></ul><ul><li>this.catalogService = catalogService; </li></ul><ul><li>} </li></ul>Inject Spring Bean <ul><li><beans> </li></ul><ul><li><bean id=“ catalogService ” class=“ service.CatalogDAO ”/> </li></ul><ul><li><bean id=&quot; itemController &quot; class=&quot;controller.ItemController&quot; scope=&quot;session&quot;> </li></ul><ul><li>< property name =&quot; catalogService &quot;> ref =&quot; catalogService &quot;/> </li></ul><ul><li></bean> </li></ul><ul><li></beans> </li></ul>applicationContext.xml
    62. 62. Spring 2.5 Dependency Injection <ul><li>public class ItemController { </li></ul><ul><li>@Autowired </li></ul><ul><li>public void setCatalogService (CatalogService catalogService) { </li></ul><ul><li>this.catalogService = catalogService; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>@Repository (&quot;catalogService&quot;) </li></ul><ul><li>public class CatalogDAO implements CatalogService { </li></ul><ul><li>} </li></ul>Inject Spring Bean <ul><ul><li>CatalogService injected by type </li></ul></ul><ul><li><beans> </li></ul><ul><li><context:component-scan base-package=&quot;service&quot; /> </li></ul><ul><li></beans> </li></ul>applicationContext.xml
    63. 63. Spring 2.5 Stereotypes and Autowiring <ul><li>@Autowired takes care of wiring , enables DI without XML </li></ul><ul><ul><li>Default is match by type, @Qualifier match by bean name </li></ul></ul><ul><li>A component scan can discover beans </li></ul><ul><li>@Component designates Spring component </li></ul><ul><li>@Controller @Service @Repository extend @Component , designate a web controller, service, or DAO component </li></ul><ul><li><beans> </li></ul><ul><li><context:component-scan base-package=&quot;service&quot; /> </li></ul><ul><li></beans> </li></ul>applicationContext.xml
    64. 64. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
    65. 65. ItemController Bean and Spring Dependency Injection <ul><li>import service.CatalogService; </li></ul><ul><li>@Component </li></ul><ul><li>@Scope(&quot;session&quot;) </li></ul><ul><li>public class ItemController { </li></ul><ul><li>private CatalogService catalogService ; </li></ul><ul><li>@Autowired </li></ul><ul><li>public void setCatalogService (CatalogService catalogService) { </li></ul><ul><li>this.catalogService = catalogService; </li></ul><ul><li>} </li></ul><ul><li>public int getItemCount() { </li></ul><ul><li>return = catalogService ().getItemCount(); </li></ul><ul><li>} </li></ul><ul><li>. . . </li></ul>Inject Spring Bean <ul><ul><li>Creates ItemController </li></ul></ul><ul><ul><li>Spring bean no need to put in </li></ul></ul><ul><ul><li>faces_config.xml </li></ul></ul><ul><ul><li>CatalogService injected by type </li></ul></ul>
    66. 66. Spring JSF Configuration in faces-config.xml <ul><ul><li>Spring's Expression Language resolver </li></ul></ul><ul><ul><li><h: outputText value=&quot;#{ itemController.item.name }&quot; title=&quot;Name&quot; /> </li></ul></ul><ul><ul><li>JSP </li></ul></ul><ul><ul><li>Expression </li></ul></ul><ul><ul><li>Language </li></ul></ul><ul><ul><li><beans> </li></ul></ul><ul><ul><li><context:component-scan base-package=&quot;controller&quot; /> </li></ul></ul><ul><ul><li></beans> </li></ul></ul>applicationContext.xml Will scan for components, don't have to configure managed beans in faces-config.xml <application> <variable-resolver> org.springframework.web.jsf.el.SpringBeanFacesELResolver </variable-resolver> </application>
    67. 67. Spring JSF Configuration in web.xml <ul><ul><ul><li>for intercepting request to JSF </li></ul></ul></ul><ul><ul><ul><li>bootstrapping Spring's web application context </li></ul></ul></ul><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/ applicationContext.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>
    68. 68. Rest of JSF stays the same <ul><li>Spring Web Flow can also be used with JSF, but not was used in this example </li></ul>
    69. 69. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
    70. 70. Catalog Spring Bean Using JPA @Repository @Transactional public class CatalogDAO implements CatalogService { @PersistenceContext (unitName=&quot;PetCatalogPu&quot;) private EntityManager em; @Transactional(readOnly=true) public List<Item> getItems (int firstItem,int batchSize) { Query q = em. createQuery(&quot;select object(o) from Item as o&quot;); q.setMaxResults(batchSize); q.setFirstResult(firstItem); List<Item> items= q.getResultList(); return items; } Component Stereotype Spring transactions use aop
    71. 71. Configuration of catalogService Spring Bean in aplicationContext.xml <ul><li><beans> </li></ul><ul><li><context:component-scan base-package=&quot;service&quot; /> </li></ul><ul><li>. . . </li></ul><ul><li></beans> </li></ul><ul><li>Spring will scan for components in the service package </li></ul><ul><ul><li>Configuration is done with matching type </li></ul></ul>Scan for components
    72. 72. Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
    73. 73. JPA Entity stays the same @Entity public class Item implements Serializable { @Id protected Long id; private String name; private BigDecimal price; public Item() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getPrice() {return price;} public void setPrice( BigDecimal name){this.price=price;} … }
    74. 74. Configuring Persistence Provider <bean id=” entityManageFactory ” class=”... LocalContainerEntityManagerFactoryBean ”> <property name=”dataSource” ref=” dataSource ”/> <property name=”loadTimeWeaver”> <bean class=”... GlassFishLoadTimeWeaver ”/> </property> <property name=”jpaVendorAdapter”> <bean class=”... TopLinkJpaVendorAdapter ”/> </property> </bean> <bean id=” transactionManager ” class=”... JtaTransactionManager ”/> <tx: annotation-driven /> <context:annotation-config/> <aop:aspectj-autoproxy/> <bean class=&quot;.... PersistenceExceptionTranslationPostProcessor &quot;/> <bean class=&quot;.... PersistenceAnnotationBeanPostProcessor &quot;/> Container managed JPA Defined data source TopLink Classfile enhancer, for lazy loading
    75. 75. Spring JPA Configuration for Derby JDBC driver <bean id=&quot; dataSource &quot; class=&quot;org. springframework .jdbc.datasource. DriverManagerDataSource &quot;> <property name=&quot;driverClassName&quot; value=&quot; org.apache. derby .jdbc.ClientDriver &quot; /> <property name=&quot;url&quot; value=&quot;jdbc:derby://localhost:1527/pet-catalog&quot; /> <property name=&quot;username&quot; value=&quot;app&quot; /> <property name=&quot;password&quot; value=&quot;app&quot; /> </bean>
    76. 76. Spring & GlassFish Application Server <ul><li>To Run Spring on Glassfish: </li></ul><ul><ul><li>Add Spring 2.5 jar files to application War </li></ul></ul><ul><ul><li>Configure .xml files </li></ul></ul><ul><li>Sample on Carol's blog : </li></ul><ul><li>http://weblogs.java.net/blog/caroljmcdonald/ </li></ul>
    77. 77. Get Spring (and this sample) from the GlassFish Update Center
    78. 78. Or Get Spring from from Netbeans Plugins catalog
    79. 79. Summary <ul><li>Spring </li></ul><ul><ul><li>Heavily AOP and POJO based </li></ul></ul><ul><ul><li>Annotation and configuration centric, but easy to test </li></ul></ul><ul><ul><li>Provides its own way for transaction management, data sources, etc </li></ul></ul><ul><li>Java EE Glassfish future: </li></ul><ul><ul><li>OSGI , faster startup , only load needed modules going into Glassfish V3 </li></ul></ul>
    80. 80. Agenda <ul><li>Catalog Java EE Application </li></ul><ul><li>Catalog Java EE Spring Application </li></ul><ul><li>Catalog Java EE Seam Application </li></ul><ul><li>Summary </li></ul>
    81. 81. What is Seam? <ul><li>Framework on top JavaEE 5 </li></ul><ul><li>Seam unifies the “ web tier ” with the “ enterprise tier ” </li></ul><ul><li>“ Glue ” for JSF and EJB3 components </li></ul><ul><ul><li>Enable EJB 3.0 components to used as JSF managed beans </li></ul></ul><ul><ul><li>Prototype for JSR 299 WebBeans , will be in Java EE 6 </li></ul></ul><ul><ul><li>Can also work with POJOs instead of EJBs </li></ul></ul>
    82. 82. WebBeans JSR 299 <ul><li>@Component </li></ul><ul><li>@SessionScoped </li></ul><ul><li>public class Credentials { </li></ul><ul><li>private String username; </li></ul><ul><li>private String password; </li></ul><ul><li>... </li></ul><ul><li>} </li></ul><ul><li>public class Login { </li></ul><ul><li>@In Credentials credentials; </li></ul><ul><li>... </li></ul><ul><li>} </li></ul>Component: Managed class can be injected Gavin King JSR 299 lead, Sun, Google , Oracle... members Component: Definition of Managed class when name is requested, instantiated Scope: Context Buckets where the component instances are stored
    83. 83. Bean Validation Framework JSR 303 <ul><li>Bean Validation Framework JSR 303 going into Java EE 6 </li></ul><ul><li>@Entity </li></ul><ul><li>public class Address { </li></ul><ul><li>@Max(9) @NotNull </li></ul><ul><li>private String zipcode; </li></ul><ul><li>} </li></ul>Emmanuel Bernard (Red Hat) JSR 303 lead, Sun, Google, Oracle... members
    84. 84. Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
    85. 85. Seam Key Concepts <ul><li>Eliminate the ManagedBean – bind directly to any component: Entity, EJB.... </li></ul><ul><li>Components are associated with context variables using @Name </li></ul><ul><ul><li>The @Name annotation binds the component to a contextual variable – it’s just like < managed-bean-name > in the JSF XML </li></ul></ul>@Name = gives a name to reference a component Context ~= bucket
    86. 86. Seam Key Concepts <ul><li>Components are assigned a scope using the @Scope annotation </li></ul><ul><ul><li>EVENT scope -- Spans a server request , from restore view to render response </li></ul></ul><ul><ul><li>SESSION scope –http session </li></ul></ul><ul><ul><li>CONVERSATION scope --Spans multiple requests from the same browser window, demarcated by @Begin and @End methods. </li></ul></ul><ul><ul><li>Others: PAGE, APPLICATION, BUSINESS_PROCESS </li></ul></ul>Context=bucket Scope = how long stored in context bucket @Name = gives a name to reference a component
    87. 87. Seam Key Concepts <ul><li>less xml – use annotations instead </li></ul><ul><li>dependencies are injected and updated every time a component is accessed </li></ul><ul><li>Bijection – of components </li></ul><ul><li>@In private MyServiceOne service1; </li></ul><ul><ul><li>injection is applied before the method is invoked </li></ul></ul><ul><li>@Out private Item item; </li></ul><ul><ul><li>outjection is applied after the method is invoked </li></ul></ul>
    88. 88. Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
    89. 89. JPA Entity & Seam @Entity @Name(&quot; item &quot;) @Scope(ScopeType.EVENT) public class Item implements Serializable { @Id protected Long id; private String name; private BigDecimal price; public Item() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public String getPrice() {return price;} public void setPrice( BigDecimal name){this.price=price;} … } The @Name annotation binds the component to a contextual variable – it’s just like <managed-bean-name> in the JSF XML
    90. 90. Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
    91. 91. Seam JSF Configuration in faces-config.xml <application> <el-resolver> org.jboss.seam.jsf.SeamELResolver </el-resolver> </application> <lifecycle> <phase-listener> org.jboss.seam.jsf.SeamPhaseListener </phase-listener> </lifecycle>
    92. 92. Component Bindings – List.jsp ... <h:dataTable value='#{ items }' var=' dataTableItem '> <h:column> <h:commandLink action=&quot;#{ catalog . select }&quot; value=&quot;#{ dataTableItem .name}&quot;/> </h:column> <h:column> <h:graphicImage url=&quot;#{ dataTableItem .imagethumburl}&quot;/> </h:column> <h:column> <h:outputText value=&quot;#{ dataTableItem .price}&quot;/> </h:column> </h:dataTable> ... A snippet from List.jsp
    93. 93. UIComponents Binding to a Session EJB <ul><li>public class CatalogBean { </li></ul><ul><li>@DataModel </li></ul><ul><li>List<Item> items </li></ul><ul><li>@Factory (&quot;items&quot;) </li></ul><ul><li>public void getItems () { </li></ul><ul><li>... </li></ul><ul><li>} </li></ul><ul><li>. . . </li></ul><ul><li>} </li></ul><ul><ul><li><h: dataTable value =&quot;#{ items }&quot; </li></ul></ul><ul><ul><li>var='dataTableItem' </li></ul></ul>Session Bean @DataModel for exposing to page @Factory for initializing Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page
    94. 94. Catalog Session EJB @Stateful @Scope(SESSION) @Name(&quot; catalog &quot;) @Interceptors ({org.jboss.seam.ejb. SeamInterceptor .class}) public class CatalogBean implements Serializable, Catalog { @PersistenceContext(unitName=”PetCatalogPu”) EntityManager entityManager; @DataModel private List<Item> items=null; @Factory(&quot; items &quot;) public void getItems() { Query q = em.createQuery( &quot;select object(o) from Item as o&quot;); q.setMaxResults( batchSize ); q.setFirstResult( firstItem ); items= q.getResultList(); } Seam JSF DataModel component Seam Factory Method, called on initialization
    95. 95. EJB 3.0 Interceptors <ul><li>Interceptors intercept calls </li></ul><ul><ul><li>sit between caller and a bean </li></ul></ul><ul><li>basic AOP </li></ul><ul><li>Invocation model: “ around ” methods </li></ul><ul><ul><li>Wrapped around invocation of business method </li></ul></ul><ul><li>Uses: </li></ul><ul><ul><li>Auditing, logging , exception handling, security </li></ul></ul>interceptor <ul><ul><li>dataTable value =&quot;#{ items }&quot; </li></ul></ul>@Stateless public class CatalogBean { public void book(…) {} }
    96. 96. Component Bindings – List.jsp ... <h:dataTable value='#{ items }' var=' dataTableItem '> <h:column> <h:commandLink action =&quot;#{ catalog . select }&quot; value=&quot;#{ dataTableItem .name}&quot;/> </h:column> <h:column> <h:graphicImage url=&quot;#{ dataTableItem .imagethumburl}&quot;/> </h:column> <h:column> <h:outputText value=&quot;#{ dataTableItem .price}&quot;/> </h:column> </h:dataTable> ... A snippet from List.jsp Action link @DataModelSelection holds the selected value
    97. 97. UIComponents Binding to a Session Bean <ul><ul><li><h: commandLink action =&quot;#{ catalog.select }&quot; value=&quot;#{dataTableItem.name}&quot;/> </li></ul></ul>Session Bean JSF positions DataModel.getRowData() to row of action before calling action listener <ul><li>public class CatalogBean { </li></ul><ul><li>@DataModelSelection </li></ul><ul><li>@Out </li></ul><ul><li>private Item item; </li></ul><ul><li>public String select() { </li></ul><ul><li>return &quot;item_detail&quot;; </li></ul><ul><li>} </li></ul><ul><li>. . . </li></ul><ul><li>} </li></ul>Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page
    98. 98. Invoke Application Phase <ul><li><h: commandLink action =&quot;#{ catalog.select } &quot; </li></ul>@Stateful @Scope(SESSION) @Name(&quot; catalog &quot;) @Interceptors ({... SeamInterceptor .class}) public class CatalogBean implements Serializable, Catalog @DataModel private List< Item > items =null; @DataModelSelection @Out(required=false) private Item item; public String select() { return &quot;item_detail&quot;; } Action method Navigation response outject to the item context variable inject the DataModel row item corresponding to clicked Link Action method
    99. 99. Navigation (same as before) from-view to-view from-outcome Navigation rules in faces-config.xml, Or in Seam's pages.xml . list.jsp new_usr.jsp error.jsp error.jsp detail.jsp “ item_detail” new user error
    100. 100. Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
    101. 101. Standard request processing lifecycle Render Response Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations outjected item event context variable, available to JSP
    102. 102. Component Bindings – Detail.jsp ... <h:outputText value=&quot;Name:&quot;/> <h:outputText value=&quot;#{ item .name}&quot; title=&quot;Name&quot; /> <h:outputText value=&quot;Description:&quot;/> <h:outputText value=&quot;#{ item .description}&quot; title=&quot;Description&quot; /> <h:outputText value=&quot;Photo:&quot;/> <h:graphicImage url=&quot;#{ item .imageurl}&quot; title=&quot;Imageurl&quot; /> ... A snippet from Detail.jsp @Out exposes value to page outjected item event context variable, available to JSP
    103. 103. Seam & GlassFish Application Server <ul><li>To Run Seam on Glassfish: </li></ul><ul><ul><li>Add Seam jar files to application: some in War some in EJB jar </li></ul></ul><ul><ul><li>Configure .xml files </li></ul></ul><ul><li>Seam 2.0 example on Carol's blog : </li></ul><ul><li>http://weblogs.java.net/blog/caroljmcdonald/ </li></ul><ul><li>Seam 2.1 glassfish configuration : </li></ul><ul><li>http://docs.jboss.com/seam/2.1.0.SP1/reference/en-US/html/glassfish.html </li></ul>
    104. 104. Agenda <ul><li>Catalog Java EE Application </li></ul><ul><li>Catalog Java EE Spring Application </li></ul><ul><li>Catalog Java EE Seam Application </li></ul><ul><li>Summary </li></ul>
    105. 105. Summary <ul><li>Each open source project provides a different approach to how an application is built </li></ul><ul><li>Spring </li></ul><ul><ul><li>Heavily AOP and POJO based </li></ul></ul><ul><ul><li>Annotation and configuration centric, but easy to test </li></ul></ul><ul><ul><li>Provides its own way for transaction management, data sources, etc </li></ul></ul><ul><li>Seam builds on JavaEE </li></ul><ul><ul><li>Simplification of EJB3 and JSF development </li></ul></ul><ul><li>Java EE Glassfish future: </li></ul><ul><ul><li>Web Beans and Bean Validation going into Java EE 6 </li></ul></ul><ul><ul><li>OSGI , faster startup , only load needed modules going into Glassfish V3 </li></ul></ul>
    106. 106. Which one, don't ask me <ul><li>Best Tool for the Job? </li></ul><ul><li>Better Framework depends on your application requirements </li></ul><ul><li>Pick 2-3 frameworks for your type of application... </li></ul><ul><li>... and prototype! </li></ul><ul><li>If prototype doesn't meet requirements, switch </li></ul>
    107. 107. For More Information <ul><li>Glassfish </li></ul><ul><ul><li>https://glassfish.dev.java.net/ </li></ul></ul><ul><ul><li>http://blogs.sun.com/theaquarium/ </li></ul></ul><ul><li>JavaEE </li></ul><ul><ul><li>http://java.sun.com/javaee/ </li></ul></ul><ul><li>Spring </li></ul><ul><ul><li>http://www.springframework.org/ </li></ul></ul><ul><li>Seam </li></ul><ul><ul><li>http://www.seamframework.org/ </li></ul></ul><ul><ul><li>Seam in Action Book, by Dan Allen </li></ul></ul><ul><li>Carol's blog </li></ul><ul><ul><li>http://weblogs.java.net/blog/caroljmcdonald/ </li></ul></ul>
    108. 108. <ul><li>Presenter’s Name </li></ul><ul><ul><li>[email_address] </li></ul></ul>Carol McDonald Java Architect Tech Days 2009

    ×