• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JavaEE Spring Seam
 

JavaEE Spring Seam

on

  • 5,044 views

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

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

Statistics

Views

Total Views
5,044
Views on SlideShare
4,949
Embed Views
95

Actions

Likes
3
Downloads
45
Comments
0

5 Embeds 95

http://owen.com 73
http://www.slideshare.net 9
http://localhost 8
http://origoni.tistory.com 4
http://sysdecom-projects.com 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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, . 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 , , . The 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 element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The 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 , , . The 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 element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The 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 , , . The 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 element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The 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 , , . The 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 element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The 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 , , . The 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 element displays the userNumber property of the UserNumberBean and also prompts the user to enter a new number in the textfield. The 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 element. The element contains one or more 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 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 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 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 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
  • 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 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 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 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 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 JavaEE Spring Seam Presentation Transcript

  • JavaEE with Spring or Seam Carol McDonald, Java Architect
  • About the Speaker
    • Carol cDonald:
      • Java Architect at Sun Microsystems
      • Before Sun, worked on software development of:
        • Application to manage car Loans for Toyota (>10 million loans)
        • Pharmaceutical Intranet apps ( Roche Switzerland)
        • Telecom Network Mgmt app ( Digital France)
        • X.400 Email Server ( IBM Germany)
  • Agenda
    • Look at a sample application built 3 ways:
    • using Java EE,
    • Java EE and Spring,
    • Java EE and Seam
    • all running on Glassfish
  • Sample Application
  • Catalog Java EE Application
        • Persistence – JPA Entities
    DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
  • JPA Unifying/Standardizing Persistence
    • Based on existing successful technologies:
      • TopLink, Hibernate, Kodo, Java Data Object s, etc.
      • One common API for all major ORM frameworks
      • Standardized annotations @ and XML
        • xml for mapping is optional
      • Support for pluggable 3 rd party Persistence provider s
  • JPA: Simplifying/Unifying/Standardizing Persistence
    • POJO based programming/persistence model
      • Simple Java classes – not EJB components
        • Can be used in Java SE , web or EJB -based applications
        • No need for D ata T ransfer O bjects
        • Facilitates testability
    • Simpler and easier:
      • Most configuration is defaulted – configure by exception only (configure only to override default)
  • 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;} … }
  • 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
  • Relationships JPA Standardized O/R Mapping
    • Standardized o bject/ r elational m apping
      • annotations to specify how to map attributes to DB
        • xml for mapping is optional
      • Most configuration is defaulted
    Relationships
  • 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 . . .
  • 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
  • How Does it Work? Entity Manager
    • EntityManager API to manipulate entities
    • stores/retrieves entities in DB:
      • Use EntityManager methods to persist, update, delete data
        • em. persist (p); em. merge (p); em. find (p.class, id); ; em. remove (p);
      • Query using EJB QL or SQL
        • List<Passenger> listP = em. createQuery (“select p from Passenger p”) .getResultList ();
  • Persistence Context
    • ~HashMap of Managed Entity objects
      • first-level cache
      • holds (at most) one in-memory Entity for each database row
      • can do dirty checking of objects and write SQL as late as possible (automatic or manual flushing)
    • The Persistence Context has a scope, for EJBs:
      • default : same scope as the system transaction (JTA)
      • extended : the PC is bound to a stateful session bean
  • 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
  • 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); }
  • Catalog Java EE Application
        • Stateless Session EJB
    DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
  • Business Interface
    • public interface CatalogService {
    • public Item getItem(String itemID);
    • public int getItemCount();
    • public List<Item> getItems (int firstItem,
          • int batchSize );
    • }
    CatalogService Business Interface
  • 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; } }
  • Java EE: Dependency Injection
    • Dependency Injection = Inversion of Control
    • Don't call us, we'll call you (Hollywood Principle)
      • Bean specifies what it needs through @
    • References to resources are injected when instance is constructed:
      • @Resource : for connection factories, EJBContext, UserTransaction , etc.
      • @EJB : For EJB References
      • @PersistenceContext : For container-managed EntityManager
      • @PersistenceUnit : For EntityManagerFactory
  • Agenda
    • Catalog Java EE Application
      • JSF
  • JSF Component, Event Driven Web Framework
    • Pages composed of server side components
    View Root Form id=guess Managed Bean getUserNumber() setUserNumber(..) guess() Business Service guess()
      • Events call ManagedBean methods
    UIIput id=guessNum UICommand id=submit
  • What is a JSF UI Component? Some Standard Components
  • Some Open Source UI Components
  • UI Components
      • So... what is a UI component?
        • To a page author – XML tag (JSP or Facelets)
        • To a component author – component class and renderer
    maintains component state, processes input renders a user interface Component Class XML Tag Renderer
  • JSF Web Framework View Controller Model Request Service Interface Events
  • Catalog Java EE Application
        • JSF components and Managed Bean
    DB Registration Application Managed Bean JSF Components Session Bean Entity Class Catalog Item ManagedBean
  • List Items page Data Table
  • list.jsp
    • <h:dataTable value='#{ item.items }' var=' dataTableItem ' >
    • <h:column>
    • <f:facet name=&quot;header&quot;>
    • h: outputText value=&quot;Name&quot;/>
    • </f:facet>
    • <h:commandLink action =&quot;#{ item.detailSetup }&quot; value =&quot;#{ dataTableItem.name }&quot;/>
    • </h:column>
    • <h:column>
    • <f: facet name=&quot; header &quot;>
    • h: outputText value =&quot; Photo &quot;/>
    • </f:facet>
    • < h: graphicImage url =&quot;#{ dataTableItem.imagethumburl }&quot;/>
    • </h:column>
    • <h:column>
    • <f:facet name=&quot;header&quot;>
    • h: outputText value =&quot; Price &quot;/>
    • </f:facet>
    • <h: outputText value =&quot;#{ dataTableItem . price }&quot;/>
    • </h:column>
    • </h:dataTable>
  • Binding UI to Managed Bean
    • list.jsp
      • <h: dataTable
      • value =&quot;#{ itemController .items }&quot;
    • faces-config.xml
    • <managed-bean>
    • < managed-bean-name >
    • itemController
      • </managed-bean-class>
    • < managed-bean-class >
    • package. ItemController
    • </managed-bean-class>
      • <managed-bean-scope>
      • session
      • </managed-bean-scope>
      • </managed-bean>
    ItemController.java public class ItemController ... public long getItems() {
      • JSP, JSF
      • Expression
      • Language
    Managed Bean property
  • Managed Bean Value Binding
    • UI Output component value attribute :
      • The property getter is invoked when the component is rendered
      • <h: dataTable value =&quot;#{ itemController .items }&quot;/>
      • The property setter is invoked when the component input is processed
      • <h: input Text value =&quot;#{ user .name }&quot;/>
    GET SET
  • 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>
  • UIComponents Binding to a Managed Bean
    • public class ItemController {
    • private DataModel model ;
    • DataModel getItems(){
    • . . .
    • return model;
    • }
    • . . .
    • }
      • <h: dataTable value =&quot;#{ itemController .items }&quot;
    Managed Bean property Managed Bean
      • dataTable
    • useful to show a Collection in a table
    • binding to DataModel which wraps
    • a collection of data objects
    Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page
  • Managed Bean: ItemController
    • import javax.faces.model.DataModel ;
    • import javax.faces.model.ListDataModel;
    • public class ItemController {
    • private DataModel model;
    • private int batchSize = 10;
    • private int firstItem = 0;
    • @EJB private CatalogService catalog ;
    • public DataModel getItems() {
    • model = new ListDataModel (
        • catalog.getItems( firstItem,batchSize) ;
    • return model;
    • }
    • . . .
      • dataTable binds to a DataModel
    • which wraps Collection of data objects
  • 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; } }
  • Relationship Between Objects getItems() via EntityBean 1 m #{itemController.items} Item Entity Product Entity Catalog StatelessSB Item Controller list.jsp
  • List Items page Link to see Item Details JSF is event-driven, listens for actions
  • list.jsp
    • <h:dataTable value='#{ itemController.items }' var =' dataTableItem '>
    • <h:column>
    • <f:facet name=&quot;header&quot;>
    • h: outputText value=&quot; Name &quot;/>
    • </f:facet>
    • <h: commandLink action =&quot;#{ itemController.detailSetup }&quot;
    • value =&quot;#{ dataTableItem.name }&quot;/>
    • </h:column>
    • <h:column>
    • <f: facet name=&quot; header &quot;>
    • h: outputText value =&quot; Photo &quot;/>
    • </f:facet>
    • < h: graphicImage url =&quot;#{ dataTableItem.imagethumburl }&quot;/>
    • </h:column>
    • <h:column>
    • <f:facet name=&quot;header&quot;>
    • h: outputText value =&quot; Price &quot;/>
    • </f:facet>
    • <h: outputText value =&quot;#{ dataTableItem.price }&quot;/>
    • </h:column>
    • </h:dataTable>
    Click causes Action Event JSF is event-driven, listens for actions
      • JSF controller handles action events, such as submitting a form or linking to another page.
    JSF Standard request processing lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations
      • action events
    JSF is event-driven, listens for actions
  • JSF Actions
      • Command Action : Refers to a backing bean method that performs navigation processing and returns a logical outcome String
    • <h: commandLink action =&quot;#{ itemController.detailSetup } &quot; ... />
    • public class ItemController {
    • private Item item ;
    • private DataModel model ;
    • public Item getItem() {
    • return item;
    • }
    • public String detailSetup() {
    • item = (Item) model.getRowData();
    • return &quot; item_detail &quot;;
    • }
  • Navigation Example from-view to-view from-outcome list.jsp new_usr.jsp error.jsp error.jsp detail.jsp “ item_detail” new user error
  • Navigation
    • <navigation-rule>
      • < from-view -id> /list.jsp </from-tree-id>
      • <navigation-case>
      • < from-outcome > item_detail </from-outcome>
      • < to-view -id> /detail.jsp </to-tree-id>
      • </navigation-case>
      • . . .
      • </navigation-rule>
    < h: commandLink action =&quot;#{ itemController.detailSetup } />
  • Standard request processing lifecycle JavaServer Faces Lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations
  • Item Detail Page
  • detail.jsp
    • . . .
    • <h:panelGrid columns=&quot;2&quot;>
    • <h: outputText value=&quot; Name: &quot;/>
    • <h: outputText value=&quot;#{ itemController.item.name }&quot; title=&quot;Name&quot; />
    • <h: outputText value=&quot;Description:&quot;/>
    • <h:outputText value=&quot;#{ itemController.item.description }&quot; title=&quot;Description&quot; />
    • <h:outputText value=&quot;Photo:&quot;/>
    • <h: graphicImage url=&quot;#{ itemController.item.imageurl }&quot; title=&quot;Imageurl”/>
    • <h:outputText value=&quot;Price:&quot;/>
    • <h:outputText value=&quot;#{ itemController.item.price }&quot; title=&quot;Price&quot; />
    • <h:outputText value=&quot;City:&quot;/>
    • <h:outputText value=&quot;#{ itemController.item.address.city }&quot; title=&quot;Address&quot; />
    • <h:outputText value=&quot;Seller email:&quot;/>
    • <h:outputText value=&quot;#{ itemController.item.contactinfo.email }&quot; title=&quot;Address&quot;
    • </h:panelGrid>
    • <h: commandLink action=&quot;item_list&quot; value=&quot;List of Items&quot;/>
    Calls itemController.getItem().getName()
  • UIOutput component value attribute
    • <h: outputText value=&quot;#{ itemController.item.name }&quot; title=&quot;Name&quot; />
    • public class ItemController {
    • private Item item ;
    • private DataModel model ;
    • public Item getItem() {
    • return item;
    • }
    • public String detailSetup() {
    • item = (Item) model.getRowData();
    • return &quot; item_detail &quot;;
    • }
    Calls itemController.getItem().getName()
  • Get Next List of Items page
  • Invoke Application Phase
      • UICommand Action : Refers to a backing bean method that performs navigation processing and returns a logical outcome String
    • <h: commandLink action =&quot;#{ itemController.next } &quot; ... />
    • public class ItemController {
    • public String next() {
    • if (firstItem + batchSize < itemCount) {
    • firstItem += batchSize;
    • }
    • return &quot; item_list &quot;;
    • }
  • Navigation
    • <navigation-rule>
      • <navigation-case>
      • < from-outcome > item_list </from-outcome>
      • < to-view -id> /list.jsp </to-tree-id>
      • </navigation-case>
      • . . .
      • </navigation-rule>
    < h: commandLink action =&quot;#{ itemController.next } />
  • Standard request processing lifecycle JavaServer Faces Lifecycle Request Restore View Response Render Response Apply Request Values Invoke Application Update Model Values Process Validations
    • <h:dataTable value='#{ itemController.items }' var =' dataTableItem ' border=&quot;1&quot; >
    • <h:column>
    • <f:facet name=&quot;header&quot;>
    • h: outputText value=&quot; Name &quot;/>
    • </f:facet>
    • <h: commandLink action =&quot;#{ item.detailSetup }&quot; value =&quot;#{ dataTableItem .name }&quot;/>
    • </h:column>
    • <h:column>
    • <f: facet name=&quot; header &quot;>
    • h: outputText value =&quot; Photo &quot;/>
    • </f:facet>
    • < h: graphicImage url =&quot;#{ dataTableItem .imagethumburl }&quot;/>
    • </h:column>
    • <h:column>
    • <f:facet name=&quot;header&quot;>
    • h: outputText value =&quot; Price &quot;/>
    • </f:facet>
    • <h: outputText value =&quot;#{ dataTableItem .price }&quot;/>
    • </h:column>
    • </h:dataTable>
    Render Will call getItems() which will display next items
  • GlassFish Application Server
    • Java EE 5 , Toplink JPA
    • Enterprise Quality
      • GlassFish Enterprise
    • Open Source
      • Dual-licensed with GPLv2/CPE
    • Community at Java.Net
      • Sources, bug DBs, discussions at Java.Net
      • Roadmaps, Architecture Documents
    • Sample application on Carol's blog :
    • http://weblogs.java.net/blog/caroljmcdonald/
  • 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
  • Demo Demo Netbeans 6.5 JPA entity JSF pages generation from DB tables
  • Agenda
    • Catalog Java EE Application
    • Catalog Spring 2.5 JSF and JPA Application
    • Catalog Java EE Seam Application
    • Summary
  • Spring Framework Goals
    • Inversion of control container for application components and lifecycle
        • Wiring components through Dependency Injection
        • Promotes de-coupling among the parts that make up an application
    • Provide Java AOP implementation
      • allowing the separation of cross-cutting concerns
        • Logging ...
    • Facilitate unit testing
      • Allow effective TDD
      • Allow POJO classes to be unit tested outside the container
  • Spring Framework
  • What Is Spring Not?
    • Not Java EE Platform Container
      • Spring typically runs within a Java EE platform or Web container
      • Spring can run in Java SE or Java EE
      • Spring leverages and prefers to use existing standards
      • relies upon the services of the server in which it is deployed
  • Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
  • 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
  • Spring Dependency Injection
    • public class ItemController {
    • private CatalogService catalogService ;
    • public void setCatalogService (CatalogService catalogService) {
    • this.catalogService = catalogService;
    • }
    Inject Spring Bean
    • <beans>
    • <bean id=“ catalogService ” class=“ service.CatalogDAO ”/>
    • <bean id=&quot; itemController &quot; class=&quot;controller.ItemController&quot; scope=&quot;session&quot;>
    • < property name =&quot; catalogService &quot;> ref =&quot; catalogService &quot;/>
    • </bean>
    • </beans>
    applicationContext.xml
  • Spring 2.5 Dependency Injection
    • public class ItemController {
    • @Autowired
    • public void setCatalogService (CatalogService catalogService) {
    • this.catalogService = catalogService;
    • }
    • }
    • @Repository (&quot;catalogService&quot;)
    • public class CatalogDAO implements CatalogService {
    • }
    Inject Spring Bean
      • CatalogService injected by type
    • <beans>
    • <context:component-scan base-package=&quot;service&quot; />
    • </beans>
    applicationContext.xml
  • Spring 2.5 Stereotypes and Autowiring
    • @Autowired takes care of wiring , enables DI without XML
      • Default is match by type, @Qualifier match by bean name
    • A component scan can discover beans
    • @Component designates Spring component
    • @Controller @Service @Repository extend @Component , designate a web controller, service, or DAO component
    • <beans>
    • <context:component-scan base-package=&quot;service&quot; />
    • </beans>
    applicationContext.xml
  • Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
  • ItemController Bean and Spring Dependency Injection
    • import service.CatalogService;
    • @Component
    • @Scope(&quot;session&quot;)
    • public class ItemController {
    • private CatalogService catalogService ;
    • @Autowired
    • public void setCatalogService (CatalogService catalogService) {
    • this.catalogService = catalogService;
    • }
    • public int getItemCount() {
    • return = catalogService ().getItemCount();
    • }
    • . . .
    Inject Spring Bean
      • Creates ItemController
      • Spring bean no need to put in
      • faces_config.xml
      • CatalogService injected by type
  • Spring JSF Configuration in faces-config.xml
      • Spring's Expression Language resolver
      • <h: outputText value=&quot;#{ itemController.item.name }&quot; title=&quot;Name&quot; />
      • JSP
      • Expression
      • Language
      • <beans>
      • <context:component-scan base-package=&quot;controller&quot; />
      • </beans>
    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>
  • Spring JSF Configuration in web.xml
        • for intercepting request to JSF
        • bootstrapping Spring's web application context
    <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>
  • Rest of JSF stays the same
    • Spring Web Flow can also be used with JSF, but not was used in this example
  • Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
  • 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
  • Configuration of catalogService Spring Bean in aplicationContext.xml
    • <beans>
    • <context:component-scan base-package=&quot;service&quot; />
    • . . .
    • </beans>
    • Spring will scan for components in the service package
      • Configuration is done with matching type
    Scan for components
  • Catalog JSF, JPA, Spring Application DB Registration Application Managed Bean JSF Components Spring Bean Entity Class Catalog Item ItemController Spring Framework
  • 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;} … }
  • 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
  • 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>
  • Spring & GlassFish Application Server
    • To Run Spring on Glassfish:
      • Add Spring 2.5 jar files to application War
      • Configure .xml files
    • Sample on Carol's blog :
    • http://weblogs.java.net/blog/caroljmcdonald/
  • Get Spring (and this sample) from the GlassFish Update Center
  • Or Get Spring from from Netbeans Plugins catalog
  • Summary
    • Spring
      • Heavily AOP and POJO based
      • Annotation and configuration centric, but easy to test
      • Provides its own way for transaction management, data sources, etc
    • Java EE Glassfish future:
      • OSGI , faster startup , only load needed modules going into Glassfish V3
  • Agenda
    • Catalog Java EE Application
    • Catalog Java EE Spring Application
    • Catalog Java EE Seam Application
    • Summary
  • What is Seam?
    • Framework on top JavaEE 5
    • Seam unifies the “ web tier ” with the “ enterprise tier ”
    • “ Glue ” for JSF and EJB3 components
      • Enable EJB 3.0 components to used as JSF managed beans
      • Prototype for JSR 299 WebBeans , will be in Java EE 6
      • Can also work with POJOs instead of EJBs
  • WebBeans JSR 299
    • @Component
    • @SessionScoped
    • public class Credentials {
    • private String username;
    • private String password;
    • ...
    • }
    • public class Login {
    • @In Credentials credentials;
    • ...
    • }
    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
  • Bean Validation Framework JSR 303
    • Bean Validation Framework JSR 303 going into Java EE 6
    • @Entity
    • public class Address {
    • @Max(9) @NotNull
    • private String zipcode;
    • }
    Emmanuel Bernard (Red Hat) JSR 303 lead, Sun, Google, Oracle... members
  • Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
  • Seam Key Concepts
    • Eliminate the ManagedBean – bind directly to any component: Entity, EJB....
    • Components are associated with context variables using @Name
      • The @Name annotation binds the component to a contextual variable – it’s just like < managed-bean-name > in the JSF XML
    @Name = gives a name to reference a component Context ~= bucket
  • Seam Key Concepts
    • Components are assigned a scope using the @Scope annotation
      • EVENT scope -- Spans a server request , from restore view to render response
      • SESSION scope –http session
      • CONVERSATION scope --Spans multiple requests from the same browser window, demarcated by @Begin and @End methods.
      • Others: PAGE, APPLICATION, BUSINESS_PROCESS
    Context=bucket Scope = how long stored in context bucket @Name = gives a name to reference a component
  • Seam Key Concepts
    • less xml – use annotations instead
    • dependencies are injected and updated every time a component is accessed
    • Bijection – of components
    • @In private MyServiceOne service1;
      • injection is applied before the method is invoked
    • @Out private Item item;
      • outjection is applied after the method is invoked
  • Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
  • 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
  • Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
  • 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>
  • 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
  • UIComponents Binding to a Session EJB
    • public class CatalogBean {
    • @DataModel
    • List<Item> items
    • @Factory (&quot;items&quot;)
    • public void getItems () {
    • ...
    • }
    • . . .
    • }
      • <h: dataTable value =&quot;#{ items }&quot;
      • var='dataTableItem'
    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
  • 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
  • EJB 3.0 Interceptors
    • Interceptors intercept calls
      • sit between caller and a bean
    • basic AOP
    • Invocation model: “ around ” methods
      • Wrapped around invocation of business method
    • Uses:
      • Auditing, logging , exception handling, security
    interceptor
      • dataTable value =&quot;#{ items }&quot;
    @Stateless public class CatalogBean { public void book(…) {} }
  • 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
  • UIComponents Binding to a Session Bean
      • <h: commandLink action =&quot;#{ catalog.select }&quot; value=&quot;#{dataTableItem.name}&quot;/>
    Session Bean JSF positions DataModel.getRowData() to row of action before calling action listener
    • public class CatalogBean {
    • @DataModelSelection
    • @Out
    • private Item item;
    • public String select() {
    • return &quot;item_detail&quot;;
    • }
    • . . .
    • }
    Client Server A B C Backing Bean Form c1 A c2 B c3 C c1 c2 c3 A B C Page
  • Invoke Application Phase
    • <h: commandLink action =&quot;#{ catalog.select } &quot;
    @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
  • 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
  • Seam Catalog Application DB Session EJB Entity Seam Framework JSF Components CatalogBean Item
  • 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
  • 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
  • Seam & GlassFish Application Server
    • To Run Seam on Glassfish:
      • Add Seam jar files to application: some in War some in EJB jar
      • Configure .xml files
    • Seam 2.0 example on Carol's blog :
    • http://weblogs.java.net/blog/caroljmcdonald/
    • Seam 2.1 glassfish configuration :
    • http://docs.jboss.com/seam/2.1.0.SP1/reference/en-US/html/glassfish.html
  • Agenda
    • Catalog Java EE Application
    • Catalog Java EE Spring Application
    • Catalog Java EE Seam Application
    • Summary
  • Summary
    • Each open source project provides a different approach to how an application is built
    • Spring
      • Heavily AOP and POJO based
      • Annotation and configuration centric, but easy to test
      • Provides its own way for transaction management, data sources, etc
    • Seam builds on JavaEE
      • Simplification of EJB3 and JSF development
    • Java EE Glassfish future:
      • Web Beans and Bean Validation going into Java EE 6
      • OSGI , faster startup , only load needed modules going into Glassfish V3
  • Which one, don't ask me
    • Best Tool for the Job?
    • Better Framework depends on your application requirements
    • Pick 2-3 frameworks for your type of application...
    • ... and prototype!
    • If prototype doesn't meet requirements, switch
  • For More Information
    • Glassfish
      • https://glassfish.dev.java.net/
      • http://blogs.sun.com/theaquarium/
    • JavaEE
      • http://java.sun.com/javaee/
    • Spring
      • http://www.springframework.org/
    • Seam
      • http://www.seamframework.org/
      • Seam in Action Book, by Dan Allen
    • Carol's blog
      • http://weblogs.java.net/blog/caroljmcdonald/
    • Presenter’s Name
      • [email_address]
    Carol McDonald Java Architect Tech Days 2009