You are on page 1of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION

17/10/09 18:17

Introduction
Do you need to set up distributed applications? Which more is, with a simple, powerful, and easily maintainable architecture? EJB will certainly answer your waiting. Moreover, behind this name, there are several technologies: one allowing managing the conversation on the network, another to supervise the data base... and well of others still. The common point between them is that you externalize on an application server logic trade of an application. Thus, as this part treated, you will have to write the "frontal" part of your application (see ?architecture Java EE?).

To help you to conceptualize this technology, we advise you to compare this technology with a brain, because it?s the central place of the application. Lobes fill of the distinct functions: memories, reflexion, communication, etc. the same way, there is EJB various parts which fill the different roles.

EJB Presentation
What does EJB mean?
Written in the programming ?Java? language, an enterprise bean is a component on server side which encapsulates logic part of an application. Logic part is the code which achieves the goal of the application. Let us take the example of an application of inventory control, the enterprise beans could implement logic trade in methods called checkInventoryLevel() and orderProduct(). By calling upon these methods, the distant customers can reach the services of inventory provided by the application. As we will see at the time of EJB practical application, it is necessary to have an application server in order to lodge an application based on EJB. Indeed, this one must provide many mechanisms making it possible to manage the authorities of EJB, to make secure, share the application on a grid of calculation... etc. At the moment, we?ll base ourselves only on the specifications of EJB. The specifications are texts produced by expert groups from companies like Sun, IBM, Oracle... etc, in order to define bases common to all application servers.

EJB advantages
We?ll realize at the end of this essential that EJB make possible to separate the application layers in a clear way. Indeed, the functionalities suggested fit in an organization of the effective project. The separation of software in various parts makes it possible to understand what one is building: What will be the complete picture The responsibilities the subsystems and the developers How to manage the growth of the system Where the problems can appear? To prepare with changes in the needs or the approaches of implementation: Understand the limits of what you can really manage Know what you would have to change or build to satisfy Belong stable with the addition of new needs? ... Moreover, EJB are components of very high level. That means that the concepts that we will see are very powerful and are really simple to set up. Most of the time, the programmer will have only to take into account the constraint trade of his project, and to configure simple classes by means of some annotations. We will reuse without any reflection to account for the concepts like IO, RMI or JDBC, however, only the application server will have to use these technologies.

When should you use EJB?
You should use the ?enterprise beans? if your application must respect one of the following conditions: The application must be easy to update. To adapt to an increasingly significant number of users, you can need to distribute the components of an application through multiple machines. The enterprise beans of an application can operate on various machines, but also their localization will remain transparent for the customers

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 1 of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION
The application must be transactional. EJB support the transactions, the mechanisms which control the access convergent to the shared objects The application will have different kinds of customers. With only some lines of code, the distant customers can easily locate EJB. These customers can be light, various and numerous.

17/10/09 18:17

EJB types
The table below summarizes the three types of EJB: Table 1. EJB Types Type Entity Timer Goal Represent an entity which exists in persistent storage Allows to plan tasks at precise hours

Session Carry out a task for a customer. Apply a service Web Message Acts like a listener for API Java Message Service, treating the asynchronous messages

We?ll have in this essential only about Beans of type Session, Message and Entity because they are usually used. Those of Timer type will be seen in a more advanced course on EJB.

EJB3 changelog
Specification 3 of EJB was elaborate in order to simplify the model of design of EJB. Here are the principal points which were simplified: Simplification of the definition of the interfaces, suppression of a good number of necessary points in version 2.1 (more need to inherit a super interface or class) Simplification for the creation of the class of Bean. Simplification of API for the access to the environment of Bean: definition by simple dependent injection Introduction of the use of the annotations as Java who are used in the place of the descriptor of deployment Entity Beans are simple POJOs annotated. The mapping relational-object can be declared in the form of annotations. Entity beans have greatly been improved during its third version. The specification defines that a bean written with API EJB3 must be able to be a client with a component writes with the API 2.1 (2 & 1 also). That has of course like objective to facilitate the migration of the existing applications or simply the use of those in the new applications. Knowing that EJB version 3 go back to semi-2006, it acts of a still young technology, which begins only its phase of adoption with industry. EJB 2 is still used even if that is not a doubt that they will migrate gradually towards the new specifications.

Concepts
We will approach, in this part, the whole of EJB concepts. We will explain the various types of existing EJB but also their differences and their uses.

EJB architecture
An EJB architecture is made up of at least 3-tiers: a customer (ex: Web, heavy customer...), applicative logic (EJBs) and a data base (ex: base relational, LDAP, ERP...).

In this architecture, EJB are located in the third "applicative logical". EJB implement logic trade of the application (for the Session part) and represent an abstraction of the access to the data base (for the Entity part). However, architecture EJB is before a whole evolutionary architecture. It is then possible to make evolve a simple application EJB to an application directed Business To Business being connected towards other systems of company.

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 2 of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION

17/10/09 18:17

In this architecture, EJB are located in the third "applicative logical". EJB implement logic trade of the application (for the Session part) and represent an abstraction of the access to the data base (for the Entity part). However, architecture EJB is before a whole evolutionary architecture. It is then possible to make evolve a simple application EJB to an application directed Business To Business being connected towards other systems of company.

The preceding diagram is the structure of an EJB server. Even if the container has the most important role, it?s the server which switches the whole of the requests and manages the whole of the containers and services. The server must manage, moreover, one whole of services of infrastructure common to the whole of the containers or the services. The specification Java EE obliges the server to offer a service of directory JNDI and a service of transaction. Of course, application servers generally provide other services as a data base integrated or the security management. The goal is to facility the development, the deployment, etc... We can compare server EJB as an orchestra. The role of this server is to be the leader. It is him which directs the whole of the services and their cycle of life (starting, stop, pause...). Each part of the orchestra corresponds to a service (EJB, Transaction, Base data...). They all are independent, but they work together to produce a common result. EJB server EJB server manages whole of the services systems for EJB, and also manages the containers which authorities of EJB (called "beans") are carried out. EJB container A container, it is before all a "block box" which manages: communication with the services of infrastructure applications and their cycle of life related to the customers The container works of par with the server, providing, with them two, the environment of execution for EJB. The container simplifies the life of the developer thanks to a reduction of the codes to be built, a simplification of the treatments (automatic treatments), and a reduced maintenance (separation of the layers by levels of abstraction). Indeed, the container is at the same time an application managing of the applications but also a tool which generates code for each EJB. It is also the container which will make it possible the developer to use the services of infrastructure available within EJB server as connection to the database, the management of the transactions...

The main role of container EJB is, however, to manage the cycle of life of the applications EJB which are associated for him. It is him which deploys them, stops them and redeploys them, while managing their conformity with the

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 3 of 100

the variables of authorities of this component are then related to the customer and their values preserved of a call of method at another. this one carries out the method and turns over possibly the result. Whereas Entity Bean (explained in the following chapter) is used to reach the data (addition. for example. the partitions and the environment necessary to the musicians (represented by EJB). The choice of the type Stateless or Statefull is based on the interaction wished between the customer and the Bean Session. to reserve a travel. To continue the metaphor of the orchestra. https://www. 17/10/09 18:17 What is a Session Bean? A Bean Session is component an applicative side server making it possible to provide one or more services to various customer applications.campus-booster. This type of execution is typically the same one as that of protocol HTTP (mode offline). It can also represent a workflow. Moreover. Indeed. the work and the maintenance of association constitute an important additional task for the container. The advantage of the Stateless type is its capacity to be gone up in load. 3. However.. This type of Bean Session thus consumes more memory that the Stateless type. to recover the list of the products of a shop. Beans Sessions are as "frontage" between the customers and the data. EJB is divided by all the methods for a single customer. In the case of Statefull. the developers do not have to be worried some. each customer is related to an authority of EJB (fig.aspx?lecture=814&PM=True Page 4 of 100 . The virtual caddie is the most common example to illustrate the use of Statefull Session Bean.).. A service is useful. according to the specification. it is a "block box" which.). It introduces the concept of session between the customer and the server. suppression.. State management There are two types of session beans: stateless and statefull. It also makes it possible to control the components which are with its load. It results from it a worse rise in load and sometimes degradation from the performances when an application uses the Statefull type wrongly and without reason. Even if the container is the central point of the execution of EJB. several customers use the same authority of EJB in a concurrent way.net/Booster/Pages/lectureSimpleViewer. each authority of Statefull Session Bean is associated to a single customer. Stateful session bean Statefull Session Bean is an extension of the customer application. is carried out according to certain well defined events.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION specifications of the server. The server of application can use a system of plug ("swap") for preoccupations with an optimization of memory (concept of passivation) Statefull Session Bean is usually used to manage a process being carried out in several stages (purchases on a going site. modification. The Beans Session thus constitutes bricks of logic trade of an application. the container is the person who prepares the instruments.2). One speaks precisely about conversational state to qualify this type of communication. Statefull Session Beans tend to being specific to the application. to send a newsletter. When a customer application calls a method of a Bean Session. So a method called on EJB can read or modify information on the conversational state.. They treat the data and carry out the operations related to the logic of the company. that doesn?t mean that in any case that Statefull Session Bean is persistent. to record a reservation or to check the validity of a stock. As we detailed at the beginning of this part. Stateless session bean Stateless Session Bean is a collection of services gathered around the same subject. Stateless Session Beans tend to being general in order to be able to be re-used in other contexts. This type of component maintains the state conversational with the customer. Stateless means that the service is autonomous in its execution and thus which it does not depend on a particular context. A Bean Session can be regarded as a storyboard in the world of cinematographic animation: it defines the successive stages in order to lead to a final objective. The execution is not worried what could be made before or what could be made afterwards. Bean Sessions are divided into two types: "Stateless" and "Statefull". The important point lies in the fact that no state is preserved between two invocations of methods. Contrary to the Stateless type.

application being carried out one the same server of applications) and the methods of communication.). A sale is carried out after several stages: Choice of the articles Creation of a clients' account or use of an existing account Choice of the payment of the order Payment Recording of the order It is imperative to safeguard the state of the conversation between these various stages in order not to lose information. Thus.aspx?lecture=814&PM=True Page 5 of 100 . It is then more possible only one customer modifies the same object of another customer. moreover. EJB define the way in which the various announcers of year structures Java EE interact. On the other hand. Within the framework of a distant sight. etc. the possibilities offered to the various customers (Java application. a EJB places at the disposal its methods with customers being carried out on different virtual machines. The principal difference between these two types is undoubtedly the local access or the remote access. but it will be necessary to take into account the fact that they are not completely equivalent (in particular on the level of safety with the passages by reference/valor). the uses of has local sight makes it possible to optimize the performances of the server of application and to minimize the resources. Unfavorable it?s necessary then to consider that various customers handle the same object At the same time and thus to anticipate the effects that that edge induce.. Local visibility By adopting has local sight (room) for has EJB. application being carried out on the same server of applications) and the methods of communication.. applet. The objects having to be "transportable" remotely. If the customer application is carried out within the same virtual machine then the local sight certainly will be adapted and conversely for the remote sight. Web services visibility The webservices are spread more and more on Internet. He results has weaker demarcation from it from EJB with respect to his customers. How to choose your connection? The adoption of a local or distant sight decides at the time of the creation of EJB. it will possible to define EJB according to two prospective customers for the customer: local sight (room) has and has distant sight (remote). applet. and thus on different physical machines (applet. EJB define the way in which the various speakers of architecture Java EE interact.) is whitebait to call the methods of this EJB. the arguments and values of return must be serialized and are not transmitted any more by reference. It is possible to specify the visibility of your EJB with the webservice type so that it can be used with the manner of a webservice. However. the container owes serialize/unserialize these objects to transmit them via the network. and it is thus easier to delimit the various fields of safety. In this sight.. moreover. for the customer to directly modify the recovered objects.campus-booster..net/Booster/Pages/lectureSimpleViewer. It results from it from the higher processing times compared to the local calls. 17/10/09 18:17 Access to the Session Bean Beyond the simple delimitation of the various applicative layers. It is completely possible simultaneously to consider the use of these two sights. the demarcations are stronger between an EJB and its customer. It is however possible to support the local accesses while placing an intermediary (the container Web) between EJB and https://www. Remote visibility By adopting a distant sight (remote). Beyond the simple delimitation of the various applicative layers. The choice should not be generic. The arguments passed by possible reference and it are. because they make it possible to use any service starting from any language. but must be made compared to the needs for the application.. the calls of method of EJB by the customer are carried out have in any traditional Java application (Java SE). applications Java.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Let us take the example of a site of trade online. it will be possible to define EJB according to two prospects for the customer: a local sight (room) and a distant sight (remote). They define.. They define. servlet .). the possibilities offered to the various customers (Java application. The calls of methods are done via technology RMI. This technology misses maturity however and must for the moment to remain on the level of the concerns of technological survey. The basket can be modeled thanks to Statefull Session Bean. One the other hand. the use of a distant sight has also disadvantages. This one does not cuts then to Be occupied of specificities related to transport via the network (not of serialization of the objects. No communication network. this choice is restricted with EJB of the type Stateless Session Bean. Thus. any customer carried out in the same virtual machine (another EJB.

placed at the disposal by the orchestra (" Business to Business ").campus-booster. the services offered are ?static?. the local side would be that of a spectator present in the room and the remote side that of a spectator listening to on his radio the repeat broadcast placed at the disposal by the orchestra. Statefull Session Beans are suitable if one of the following conditions (not exhaustive) is true: The state of Bean represents the interaction between Bean and a particular customer. it exists only for one short duration (approximately a few hours). it can be judicious to give them the access to such a Web Service.1. Indeed. i.aspx?lecture=814&PM=True Page 6 of 100 . JBoss Messaging (in the past JBoss MQ). It is the solution Java EE with the concept of the MOM (Message Oriented Middleware). The applications using JMS are independent of the type of server to which they are connected since they use the API JMS. In all the cases. Architecture JMS is made up of various elements: a supplier consumer https://www. but largely simplifies the development of these components. presenting a sight simplified at the customer. is to be used when the customer is not written as Java or when you wish to render your service most open possible. However. In such cases. only one customer has access to the authority of the Bean Session. The choice of the type of Bean Session is not always obvious. When to use a Session Bean ? Here some conditions concerning the use of the Beans Session in a system of company: At any moment. to send an email confirms an order on line. The concept of MDB (Message Driven Bean) was introduced with EJB 2. That means that the applications communicating via JMS cannot be carried out at the same time. could recover the lines of a table which represent the products which are on sale this month. Since version 2.0 in order to treat the messages coming from a supplier JMS (Java Message Service). The applications generally use JMS in architectures of the type B2B (Business to Business). The state of Bean is not persistent. it is necessary to include/understand a sending of data directly interpretable and usable by the other applications.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION the distant customer.net/Booster/Pages/lectureSimpleViewer. The service can be accessible also via a service Web. The side webservice would be that of an external TV channel. Bean must store the information concerning the customer during the execution of the methods. Bean makes the connection between the customer and other components of the application. The sight webservice. Typically. in a large majority of the cases. It may be that it never receives answer. Many editors provide their own implementation JMS. a supplier JMS is inevitable to use the Bean Message. One Message Tail of Sun Microsystem. for example.e. 17/10/09 18:17 What is a Message Driven Bean? Presentation Within an information system of company. as for it. this API makes it possible to interconnect any system using the principle of transport where the sending and the reception of message are asynchronous.. prefer the Stateless type by defect. independent of the customer who calls them. Bean achieves a generic task for all the customers.0 must support JMS. or only one acknowledgement of delivery. Specification EJB 3. One finds MQSeries from IBM. Such Bean. then it doesn?t receive the answer directly. This system allows the exchange of messages between various distant applications. In only one call of method. In slide. To improve performances. on the same principle as the system of electronic mail (email).. For example. The servers of transport are often ignored (contrary to the database servers). you can choose to use Stateless Session Bean if it has one of these characteristics: The state of Bean does not have a data specific to a customer. Bean recovers of a data base a unit of data in reading alone which are often used by the customers. By communication. downloading the recording in the complete concert.0 does not offer really new functionality. others provide the supports to question other implementations JMS. although they are numerous. two applications can need to communicate. When the sender sends a request (by an email). the Beans Messages support any system of transport and are thus independent of JMS. To compare this concept with an orchestra. if you wish to give the possibility to your purchasers of consulting your catalogue of products in any manner. JMS is the API one used for the access to a system of transport of company. They are the Message Driven Beans which makes it possible to treat the messages coming from other applications. Bean controls the workflow of several Beans Company (it is thus a frontage). Send a message with JMS All the compatible servers of application EJB 3.

He occupies himself of treating the sendings and making so that they are received. In a pointtopoint model a message is transmitted only to only one application.aspx?lecture=814&PM=True Page 7 of 100 . Publishion / Subscription In this model. In the temporary case. There are two types of subscription: temporary and durable. Message transmission facility JMS offers two models of transport: pointtopoint and publication/subscription. certain companies used the pointtopoint https://www. Java. Each new message is broadcast towards each registered consumer. the pointtopoint model represents a relation ?One to One? between a message and a recipient whereas the model publication/ subscription is represented by a connection ?One to Many?.campus-booster.net/Booster/Pages/lectureSimpleViewer. the element which will forward via a communication between the customers. Peer to Peer (P2P) The pointtopoint model makes it possible to connect the customer applications between them via a queue (tail). one obliges the supplier to record the messages at the time of a disconnection.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 messages destinations Thus. one can say that they are " letter boxes " in which the messages are placed while waiting for that a customer comes to claim them. Each consumer must however have been registered beforehand on this subject if not it does not receive anything. It is exactly like the principle of a pile. the consumers receive the messages as long as they are connected to the subject. When use it? An important point in this architecture is that it allows a communication slightly coupled between the customers: a customer is not worried identity of sound or his correspondents not of their possible state. In a simple way. each of the two models has interesting characteristics. it proves that it is possible to make the same thing whatever the model used. In the case of a durable subscription. A supplier is always used as intermediary. Which mode to choose? A common problem for the architects is of knowing which model to use. However. When a customer application (consuming) is free..). The messages are sent and piled up. after some reflections. a supplieris the element has the load of the delivery of the messages between the various speakers. this system can work in heterogeneous environment (C++ application. and to send them at the time of the new connection of the consumer. as its name indicates it. A customer is an application or intervening component of application at the time of the exchanges. Indeed.. it then receives the piled up messages. The producer is independent owing to the fact that the message was received by the consumers. This model can be assimilated to a hub (material physique of network). He sends or receives the messages. To schematize. JMS provides an access on these two types of models bus to its development. a producer can send a message to several consumers by the means of a subject (topic). Moreover. one thus does not send them directly customer to another. The destinations are objects configured on the level of the supplier which are at disposal of the customers and who will be used by the latter for the sending and the reception of the messages. A message is.

they are recorded and stored in systems of persistence (bases data). but it starts to appear in the applications Java SE. With the opposite. a table in a data base gathers a whole of fields. the selected model depends on the use which one wishes to make.. Each property of this object is related to a field of the table. 17/10/09 18:17 What is an Entity Bean? Entity Beans were created to simplify the management of the data on the level of an application. More concretely. Conversely. but also to facilitate the safeguard in data base. it is common to use classes for each type of objects used. products. " first name ". In the majority of the cases. the model of subscription is less restrictive and is used more particularly for the flow of information which can be used by any customer. Persistence While shortening. a table is related to another table by a foreign key (fig. but User Subscription would be a Bean Session.. via Mapping Objet/ Relational. This single identifier makes it possible the application to find the data of Entity Bean associated. The connection between the data and the application by an object is called the mapping(to connect). a user being dedicated to remain persistent.campus-booster. whereas the inscription of the user is a service. Like a table. in programming object. The application data are typically: users. However the persistence of the object created is carried out with API EntityManager. even after the stop of the application. a great difference exists. container EJB automatically synchronizes the state of these properties with the data base. During the execution of the program. Conversely. " email ". for example.net/Booster/Pages/lectureSimpleViewer. User would be Entity Bean. with the appearance of container lighter. The concept is older in EJB.aspx?lecture=814&PM=True Page 8 of 100 . One often speaks about trade object or entity (English Entity) to represent the characteristics of these objects. A relational field is represented. while keeping the relations between those. " telephone ". in this manner. The figure above presents the mapping between the table User and User classifies it. the data of Entity Beans generally have a long lifespan. the data of Entity Bean are preserved. these Entity Beans enable you to deal with the persistence of the data of your application in one or more data sources. Entity Bean User. These properties are called: persistent fields. Contrary to the Beans Session. Each authority of this object generally represents a recording of the table. Entity Bean has relational fields. for example. 4. Contrary to the Beans Session. corresponds to a table.. In the Java world. addresses. For example. it is possible that Entity Bean is distributed on several tables. All this information is not therefore the direct properties of the object in question. These components thus establish the relation between your application and your data bases. Warning The use of Entity Beans makes it possible to represent an entity of the application and not functionality. 4. Instance creation The creation of authority of an entity is done simply by the simple instantiation of the class by the operator new. These properties are ampped (dependent) with the fields of the associated table. and more generally in the world object. in Entity Bean.. or of the bonds towards other tables. by a property whose type is another Entity Bean (fig. However.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION model and others used the model of subscription.2). One speaks about Mapping Object/Relational when one connects. The pointtopoint model will be preferred when it be wished that only one milked recipient the message and to be sure that it is treated. We will see that in detail more below. it is possible to say that the object to be made persistent. One speaks about aggregation. invoices. Entity Bean AccountInfo. Relations There are 4 possible relations between Entity Beans: One To One (one by one): If a user can have one and single account then the relation between the user and his account is of type ?One To One? One To Many (with several) and Many To One (several with one): https://www. is characterized by properties such as: " name ". can be identified starting from its account number accountId.3). These fields represent either of information directly related to the table. a relational database with an Object application. Entity Bean follows the same principle and must all have a single identifier (key primary education). However.

A unit of persistence (Persistence Links) is characterized by the following points: A whole of Entity Beans A supplier of persistence. In the application of example. A data source. this one will make it possible the developers to optimize their applications according to the management of their Entity Beans.xml? and to place this file in repertory ?METAINF?. the class ? FinancialProduct? is abstract. MySQL. Warning You must name correctly the file ?persistence. the container will not associate any context of persistence in the application. and Oracle proposes TopLink. we can see above the diagram of the entities of the application. and written as Java). or obligations (?English jump?). Persistence unit Integral part of the framework Java EE 5. because various manufacturers propose their implementation of the engine of persistence. This connection is represented by a relation ?One To Many?.net/Booster/Pages/lectureSimpleViewer. in our software of manager of financial products. There are 3 strategies of ?mapping?: a table for a hierarchy of class a table by concrete class Strategy consisting in separating the specific fields from a class girl in a table separated compared to the table containing the data of the table relationship.. https://www. Typically. knowing that an entity can as well be an abstract class (see the key word ?abstract?) that a concrete class (notabstract). Database connection The specification defines a file which gathers the whole of information of persistence. Many To Many (several with several): A user has several leisures (hobby) and leisure can be shared with several users. the relation is of type ?Many To Many? between user and user. You must name this file: ? persistence. To illustrate this concept. You do not need to code the limits of the transaction in the bean. We will study the advantages and the disadvantages of each one of these choices later. More than one simple supplier of persistence. it is important that the entity beans work inside transactions. In this case. This file will be read by container EJB at the time of the deployment of the application. Heritage An entity can inherit another.xml?.. Indeed. PostGreSQL. like Oracle. you specify the attributes of the transaction in the descriptor of deployment of the bean. The relation between Wallet and User is of type ?Many To One? and the relation between User and Wallet is of type ?One To Many?. For JBoss it acts of Hibernate. a user has several wallets of actions. very light. the unit of persistence is it ?limps black? which makes it possible to return persisting Entity Beans. Shared access The entity beans can be divided by multiple customers. but retain for the moment which that will have of importance only on the level of the performances. The container then creates an authority of the supplier of persistence with the required parameters. or Derby (a base of data functional.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 A user can have several wallets whereas a wallet is held by only one user. Indeed. the container defines the limits for you. with the root of the project. As the customers could want to change the same data. ?Stock? and ?Jump? inherit this class.campus-booster. A junction is then made for instantiate the class girl. The unit of persistence is the key element of the management of Entity Beans within an application. If the name does not correspond. SQL Server. In this case. Then.aspx?lecture=814&PM=True Page 9 of 100 . those can as well be actions sides out of purse (?English stock?). the container of EJB provides the management of transaction.

The principal service is. for example.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Persistence Manager It acts of a device managing persistence between the data and the unit of persistence. The use of this service.. your code is clear and more easily reusable (the definition of a user is found. The calls of distant methods are done by RMI (Remote Method Invocation) whereas the calls of local methods are done directly in the JVM of the server. light customers (Web navigator). It is also possible to make communicate the external systems with a transport interapplication. This model requires that the access to the Model (service) be done since the Controller (a servlet for example) and not starting from Sight (JSP). and thus of Entity Beans.aspx?lecture=814&PM=True Page 10 of 100 . The client made the request to return in the room and paid his ticket with case (RMI). Knowing that.. as well as many development tools optimized for their creation. the management of the persistence which manages the whole of the access to the data in the memory or the data sources. The client is the public which listens to the concert. Entity Beans being standardized. the class of implementation is different according to the supplier used (defined in the file ?persistence. By defect. a customer must obligatorily be set up to be able to communicate with those. of safety. it inherits the services such as the management of the transactions. Entity Bean being an EJB. The Java customers generally use JNDI and RMI to connect and call the methods of EJB. These applications are generally written as Java.. This solution brings a simple mechanism for the access and the modification of the data.net/Booster/Pages/lectureSimpleViewer. 1. to modify the first name of a user within your application. to call the method User. of course. When to use Entity Beans? Entity Beans are carried out in the container EJB.xml? with the beacon < provider >). https://www. EJB being components server. by a retailer (HTTP.. The deployed components are recorded in the directory of the server. obviously. These customers can take several forms: An application with or without graphic interface An applet A servlet in a Web application A EJB Note You can also call a EJB in a page JSP. Moreover. So they can as well be fenestrated graphic applications (called rich customers). gets multiple comparative advantages with the direct access to the data base. however. Nevertheless. 17/10/09 18:17 The client The third customer is represented by the applications connecting itself to EJB. this technique is misadvised because it does not respect the good principles of the pattern MVC (Model Seen Controller). and. Services Web. it is also possible to be connected to a EJB with a customer written in another language via an access by Service Web (fig.) or by small advertisements (JMS).campus-booster. in the majority of the applications). like JMS. it is the container which will instantiate EntityManager and which will manage its cycle of life. Indeed.setFirstName() to carry out a rough request SQL. it is easier. EJB components are divided by directories. Entity Manager being an interface. Then the customer locates them via the API JNDI and their name JNDI. which brings to the developers of many services.10). other EJB. applications internal. Only JNDI pilot (called service provider) changes one implementation to another.

net/Booster/Pages/lectureSimpleViewer. the local view would be the spectator in the room and the distant view.campus-booster. The choice should not be generic. and in Remote mode. Indeed. in the same EAR (equivalent of the JAR for the entreprise applications) Client of the WebService type The Services Web are spread more and more on Internet. It is possible to specify the visibility of your EJB with the webservice type so that it can be used as a Service Web. it is in this class that you must program logic trade. https://www. However. but must for the needs of the application. or an other EJB Local clients A local client has the following characteristics: It must be executed on the same JVM as the EJB which it reaches. would be an spectator listening on his radio the repeat broadcast placed at the disposal by the orchestra. downloading the recording in the complete concert. an J2EE client application.we are going to study the various components that we must provide for a EJB. Typically. The creation of the proxy is with the load of the container and remains completely transparent for the customer. The whole of the methods declared in the interfaces (distant/local) will have to be implemented in this class. if you wish to give the possibility to your purchasers of consulting your catalogue of products in any manner. the parameters are passed by reference. this choice is restricted with the EJB of the type Stateless Session Bean. it can be judicious to give them the access this Service Web. The various steps in creation of a Bean Session Interfaces A client can reach a Bean Session only through the methods defined in the interfaces of the bean.aspx?lecture=814&PM=True Page 11 of 100 . they are passed by value The webservice view is to be used when the client is not written in Java or when you wish to publish your service most open possible. Bean Class (implementation) The bean class of an EJB is the class of execution of the Bean Session. We will describe in a generic way all the rules to be respected. Neither the Message Driven Beans. This authority treats the method and turns over the result to the customer. Indeed. nor Entity Beans need interface. Note In Local mode. To choose between a distant and local access The main difference between these two types is undoubtedly the local access or the remote access. We will observe these rules in the next chapter. It is however possible to support the local accesses while placing an intermediary (the container Web) between the EJB and the distant customer. The webservice view would be an external chain TV. because they allow to use any service independently of the platform or the language. placed at the disposal by the orchestra (?Business to Business?). This one can then call the methods of the object recovered without worrying about the constraints of communication. Theory In this part. These interfaces define the view that the client has on the bean. If the client application is executed in the same virtual machine then the local view will be more adapted. Distant clients A distant client of a Bean Session refers following: It can work on a different machine and a different Java Virtual Machine (JVM) from the entreprise bean which it reach It can be a web component. the call of a method is automatically transmitted to the authority of EJB in the container (generally by a system of proxy).SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 The customer recovers a reference (implementing the interface trade) EJB which it wishes to use. It can be a Web component or another EJB They must be deployed together. To take again our comparison with an orchestra.

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION

17/10/09 18:17

Annotations The annotations are « marks » in the Java code, which make it possible to configure the application. In the case of Stateless Bean Sessions, we will place @Stateless on the level of the class of implementation. For Stateful Bean Session, it is about @Stateful . We will study them in detail when we write our own EJB. Descriptors of deployment We?ll find, in the specification, the files:
application.xml

being used to declare the whole of the modules integrated in a file ?.ear?. You must specify your archive of persistence in your file application.xml with the following lines:
<application xmlns="http://java.sun.com/xml/ns/j2ee" version="1.4" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com /xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application_1_4.xsd"> <displayname>StockManager</displayname> <description>Demo application</description> <module> <ejb>StockManagerEJB.jar</ejb> </module> <module> <web> <weburi>StockManagerWAR.war</weburi> <contextroot>/stockmanager</contextroot> </web> </module> </application> ejb-jar.xml

configure the EJB in a module of a ?.jar? file (optional if the descriptors of deployment related to the applications servers are specific and depend only of them) Sun Application Server uses the files sunapplication.xml (ear), sunejb.xml (jar), sunweb.xml (war). JBoss uses the files jbossapplication.xml (ear), jboss.xml and jbosscmpjdbc.xml (jar), jbossweb.xml (war). These files make it possible to use advanced functionalities of the server of applications which are not integrated into the specifications.

Warning
The use of nonstandard functionalities (except specification) involves problems of portability of a server of applications towards another Assemblage (ou Packaging) To deliver an application Java EE 5 you must create an enterprive archival file (EAR). It is a standard archival file with the extension ?.ear? which gathers a lot?s of modules EJB, Web, Application client... like showed the following diagram (2.5).

Each archival file (ear, war, jar or rar) contains a descriptor of deployment organized and structured on model XML. This one makes it possible to define the parameters of deployment of an application (ear) or a module. Deployment The step of deployment for the developer is generally very simple. It is enough to place the packaged file in a special repertory of the server of application or to use the administration of this one. JBoss requires simply that the file is put in the folder ?deploy? of the current configuration ($ {jboss.home} /server/ {configuration} /deploy Glassfish allows the deployment by the interface of administration Web or the administration command line or by a folder ?autodeploy?. The task is however more difficult for the server of application. This one must read the contents of the archive, scan the classes (in order to detect the annotated components), mapper Entity Bean at the database, to lay down the policy of security (if it is declared), generate the classes (proxy,etc.) according to specificities of the supplier. We will more develop the subject of the servers of application in the final chapter Client Let us start by remember that the EJB are distributed objects. They thus are in a system of naming and relation

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 12 of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION
client/server. The client must carry out various steps: To parameterize the environment client. Connection to the server of naming of the server of application (JNDI) To recover, with the URL, the stub one corresponding to the class Home of EJB (JNDI/RMI) Call distants methods. We will see in detail the whole of APIs to be used for each one of these stages. Conventions of nomenclature The enterprise beans are composed of multiple elements, so it is useful to follow a convention of nomenclature for your applications. The following table summarizes conventions (the example is taken on a bean representing an Account ? Account?). Table 1. Convention of nomenclature of Enterprise Beans Element Nom de l'Enterprise Bean EJB JAR Interface Abstract shema Syntax <name>JAR <name> <name> Exemple AccountJAR Account Account

17/10/09 18:17

<name>Bean AccountBean

Classe de l'Enterprise Bean <name>Bean AccountBean

Specification of a Bean Session
The elements to be set up for a Bean Session are: The class Bean The interface business The class Bean We use the annotations @Remote or @Local to define respectively if the Bean Session provides the methods to distant or local clients. It is the same for the types of Beans Session, with the annotations @Stateless or @Stateful .
@Stateful @Remote({ RichClientService.class }) public class RichClientServiceBean implements RichClientService { }

In this example, the class is annotated with @Stateful in order to declare it as Stateful Session Bean. The annotation @Remote makes it possible to specify the distant interfaces usable by clients. Cycle of life
Stateless

Since a stateless session bean is never ?passivated?, its cycle of life has only two states: ?does not exist? and ?ready? for the call of methods trades:

The Beans Session support the following callback interceptors:
@PostConstruct

The method on which this annotation is put is called when all the dependences of injection carried out by the container and before the first call of the method trade.
@PreDestroy

The method on which this annotation is put is called at the time when the instance of Bean is destroyed (during the suppression of Bean or with the stop of the application).
Stateful

The diagram below illustrates the differents steps for a Bean Session of the Stateful type during its life.

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 13 of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION
The session bean support the following callback event:
@PrePassivate (Stateful only)

17/10/09 18:17

Allows to specify a method which will be called by container EJB when Bean was inactive and it was considered to pass this one in a serialized state. This method must be sure that the resources maintained in instance are released or serializables. We speaks about ?passivation?. The interest of this principle is to release the memory employed by unutilised Stateful for the moment. The container then can serialize the instance on an external medium (hard disk...).
@PostActivate (Stateful only)

It?s the reverses of @PrePassivate . This annotation allow to specify the method which will be called by the container when a Bean must be reactivated from its state of passivation. Bean will have to find an operational state by recovering the resources released during ?passivation?. We speaks about ?activation?.

The ?passivated? state is reserved for Stateful Session Beans because they are the only ones to share a state with the customer. The life cycle of this component starts with the first call of a business method. The container then creates an instance with the Class.newInstance method (). It injects the dependences and calls the methods annotated with @PostConstruct . The great difference with the Stateless type is that Stateful integrates the concept of ?passivation?. The implementation of this concept is specific to the container and can vary from one client to another. In all the cases, the container calls the methods annotated with @PrePassivate and @PostActivate at the time of the passivation and the activation of the component. The instance is removed when the customer calls a method annotated with @Remove or when the time assigned for the session is exceeded (?timeout?). Exemple Here a very simple example of SessionBean (stateless type). The interface should of course be defined that our bean will implement. Here we define simply the Remote interface which contains only one method: getHello (). Moreover let us annotate it with the annotation @Remote in order to declare it like distant interface. Here the code of the distant interface (Remote):
import javax.ejb.Remote; @Remote public interface RemoteHello { public String getHello(); }

The bean class implements the preceding interface and is annotated by @Stateless in order to declared it as Session Bean Stateless. Here the code of this class:
import javax.ejb.Stateless; import com.society.testejb3.interfaces.RemoteHello; @Stateless public class HelloBean implements RemoteHello { public String getHello() { return "Hello world"; } }

Dependence between Beans Session As we see previously with Entity Manager, you can specify to the container that your EJB is on another. The container will be given the responsability automatically to inject the required instance. It?s why, you just have to annotate the property with @EJB. Here, an example using this annotation:
@Stateful @Remote( { RichClientService.class }) public class RichClientServiceBean implements RichClientService { @EJB private CommonService commonService; }

The RichClientServiceBean class defines a variable of instance commonService whose type is CommonService (the business interface related to the EJB). With the annotation @EJB positioned on this property, the container automatically injects an instance of the EJB ( CommonServiceBean ) when the instanciation of the EJB RichClientServiceBean . I.e. it makes, in your place, JNDI research and the automatic initialization of the dependence towards this EJB. For certain more complex cases, the annotation @EJB admits attributes which allow to specify the localization of the EJB.

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 14 of 100

0).lookup("ConnectionFactory"). Localization of bean with JNDI Here an example allowing a client to recover a reference towards the Session Bean RichClientServiceBean . While JNDI is used to locate and reach the EJB in a transparent way. Session session = cnx. EJB. we finds in particular the URL of the register. https://www. Destination destination = (Destination) jndiContext.. @Stateful or in the descriptor of deployment with the markup <ejbname> ). Moreover."127. ctx. The session is used to group the operations of sendings and receptions of messages. ctx. Use of JMS and the Message Driven Bean ConnectionFactory and Destination To work with JMS..put("java. The other element to recover is the destination. the client reaches with interfaces to beans and their business logic. File system.naming.NamingContextFactory").createConnection(). its methods do not authorize the concurent access. Connection and Session The ConnectionFactory object makes it possible to create a connection with supplier JMS.0. Warning the annotation @EJB in a rich customer application (console or graph) is available only when this one is launched in the ? Application Container Client? (AAC)."org. // le nom JNDI par défaut est // "Nom du fichier EAR/Nom de la classe du bean/type accès : local/remote" richClientService = (RichClientService) ctx. i.0. In the majority of the cases. Indeed. Moreover. in the same way that DataSource provides a connection JDBC. Once connection created.url. It represents the place on which the application wishes to work (sending or reception of message). the injection has its limits and is available only within one container.url". this adresse IP should be modified. Indeed.aspx?lecture=814&PM=True Page 15 of 100 . the first stage is to connect itself to supplier JMS. Generally. There are many suppliers of directory. a single session is sufficient.1 address.factory. the first two parameters are specific to JBoss and the values correspond to objects located in the bookshops client of this server. The installation of this type of application is explained hereafter. Here an example detailing the recovery of ConnectionFactory and a Destination: Context jndiContext = new InitialContext().0.factory.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 beanName Specify the name of the EJB (specified by the attribute name of the annotations @Stateless ."org.campus-booster. The principle is the same for a client in a Web application. We will see in the following part that there are two types of destinations: topics and tails.net/Booster/Pages/lectureSimpleViewer.createSession(true.interfaces. The client view The client of a EJB does not work directly with EJB system. JNDI is a standard in java. the Session object is ?threadsafe?. beanInterface Specify the business interface that we wish to use.).0. try { Context ctx = new InitialContext().jnp. However. These interfaces gather the API JNDI (Java Naming Directory Interface) and an API EJB Client. API EJB Client is a whole of interfaces and classes which the developer uses to work with the beans. here with the 127. This attribute is mainly indicated when you use an interface related of the business interface implemented by Bean. the thread which creates the Session object uses the producer and the consumer of this session. ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.jboss. ConnectionFactory provides a connection JMS to the service of routing of message. The creation of several sessions is useful only in the case of ?multithread? application which produce and receive messages at the same time. It is necessary to recover a ConnectionFactory object with JNDI which makes connection possible with the supplier.lookup("StockManager/RichClientServiceBean/remote").initial". an application console or another EJB. We will see in this chapter several small examples of code allowing to locate/reach/work with the beans. it is used to create a session. It allow to standardize connection to a service of directory.jnp.1:1099"). each one of them must provide its own driver for its type of directory (LDAP. like does it JDBC for databases. You will find a complete code in the chapter: EJB with practice. Connection cnx = connectionFactory. EJB3 Specification wishes to hide these JNDI calls which often diverted the developers.naming:org.put("java. } catch (NamingException e) { // gestion des erreurs } The object ?Context? allow to initialize the parameters of connection to the directory to communicate with its. This object can be compared to a DataSource (in JDBC). Among the parameters of the example.lookup("queue/MyQueue"). ctx.put("java. Thus when the server of application is not on the same machine that the client.interfaces"). The default interface is used by the variable which is subject to the injection mappedBy Specify JNDI name to be used to seek the instance of Bean.naming.provider.pkgs".e.naming.

put("java.url".send(mapMsg). TextMessage message = session.enterprise. MessageProducer producer = session. Another solution consists in sending a serializable object directly : StockAction stock = new StockAction().lookup("queue/StockValue"). Session . MessageProducer and MessageConsumer The last step is the sending and the reception of messages. Here values used for GlassFish: Hashtable hashtable = new Hashtable(). cnx. The properties for the creation of Context JNDI are dependent on supplier JMS used.createConnection(). stock.BUY_STOCK) . // [.lookup("ConnectionFactory"). this one manages the transactions and the acknowledgements of delivery according to the parameters of deployment.AUTO_ACKNOWLEDGE). producer.. MessageConsumer consumer = session.250). The heading is composed of information of destination. Let us take the case of MapMessage . the specification indicates that the value of these arguments is ignored within container EJB. StockAction. priority. which are BytesMessage and StreamMessage . Connection cnx = connectionFactory. mapMsg..setObject(stock).Message . Here those for JBoss: Hashtable hashtable = new Hashtable().campus-booster.factory. The body of the message contains data being able to be various types: Text with TextMessage .sun. "com. public class JMSSender { public void sendMessage(String text) throws Exception { Context ctx = new InitialContext().naming.aspx?lecture=814&PM=True Page 16 of 100 . hashtable.jms. ConnectionFactory connectionFactory = (ConnectionFactory) ctx. Connection cnx = connectionFactory.createProducer(destination). Destination destination = (Destination) ctx. stock. objectMsg.). Serialized object with ObjectMessage . producer. hashtable. mapMsg. expiry. Map with MapMessage .setCompany("JavaCorp").setString("company". This information would be transmitted in an object of the MapMessage type: MapMessage mapMsg = session. ObjectMessage objectMsg = session. "iiop://localhost:1050/").net/Booster/Pages/lectureSimpleViewer.naming. a message is a Java object made up of a heading and a body.naming.put("java.createProducer(destination). "com.naming. Destination .] cnx.SerialInitContextFactory").close().createConnection().. } } We find the whole of the components quoted previously ( ConnectionFactory .setAction(StockAction. int acknowledge) 17/10/09 18:17 However. The good practices of development encourage to close connections once the work is completed.close().setNumber(250). Type of Message In JMS.. Indeed.url. It is necessary to create objects of the type MessageProducer and MessageConsumer respectively to send and receive messages.createSession(false.BUY_STOCK). Clients Applications There are various interfaces according to the model of message used.send(message).factory. MessageProducer producer = session. Warning Certain suppliers do not adhere completely to the specification and are not unaware of the parameters.createTextMessage(). Each one of these types of messages inherits javax.enterprise. Two other types of messages are available to treat array of bytes and the primitive types.naming").setInt("number".. Session session = cnx. queueSender.createMapMessage() .. Those use data flows. where a message asks for the purchase of 250 actions of the company ? JavaCorp?.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION The method createSession() need two parameters: createSession (boolean transacted. However an interface common to both models exists and provides a whole of sufficient methods in the majority of the cases! Producing client Here an example of client application which is used to produce and to send messages.setInt("action". mapMsg.initial".put("java.pkgs". hashtable. stock.provider."JavaCorp") .sun. Each method takes in parameter the destination on which the object is connected.createObjectMessage(). Session. https://www.send(objectMsg). Context jndiContext = new InitialContext(hashtable).createConsumer(destination).

factory.put("java. Context jndiContext = new InitialContext(hashtable). Correspondence between the generic interfaces and those specific to the ?pointtopoint? transport Generic Destination Session MessageProducer Specific « point to point » Queue QueueSession QueueSender ConnectionFactory QueueConnectionFactory Here a summary table of the specific interfaces which can be used for a transport of the type ?subscription?: Table 3. the consumer can use more specific interfaces for each model of transport. But the implementation of MessageListener is necessary if the MDB works with JMS. hashtable. we use the concept of listener avoiding any blocking of the application when the reception of a message. } } In this example. ConnectionFactory connectionFactory = (ConnectionFactory) ctx.initial". Only the annotation @MessageDriven is necessary to define your class as MDB. "com. Here a summary table of the specific interfaces which can be used for a message of the ?pointto point? type: Table 2. MessageConsumer consumer = session.put("java.createConnection(). Note These data are as an indication and can change according to the evolution of the various versions of these server of application. "org. cnx.naming"). public class JMSReceiver { public void receiveMessage() throws Exception { Context ctx = new InitialContext(). hashtable.put("java. For that.campus-booster.aspx?lecture=814&PM=True Page 17 of 100 . @MessageDriven(name = "StockValueListener".lookup("ConnectionFactory"). By the same way as the producer. } }).pkgs". Correspondence between the generic interfaces and those specific to the ?pointtopoint? transport Generic Specific « point to point » MessageConsumer QueueReceiver Here a summary table of the specific interfaces which can be used for a standard transport ?subscription?: Table 5. the only things which differ are the recovery of MessageConsumer and the sending of the message. Session session = cnx.lookup("queue/StockValue"). Correspondence between the generic interfaces and those specific to the transport by ?subscription? Generic Specific « subscription » MessageConsumer TopicSuscriber Writing of a Message Driven Bean (consuming messages) The class of Bean Now in EJB 3.net/Booster/Pages/lectureSimpleViewer.factory.setMessageListener(new MessageListener() { public void onMessage(Message message) { System.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 hashtable.AUTO_ACKNOWLEDGE). Here a summary table of the specific interfaces which can be used for a transport of the ?pointto point? type: Table 4. Session.interfaces.naming.createSession(false. Indeed. The method onMessage (Message message) is then called automatically at the time of the reception of a message Warning Do not forget to start connection with the method start() if not no message will be received.url.createConsumer(destination).naming. https://www.println(message). Correspondence between the generic interfaces and those specific to the transport by ?subscription? Generic Connection Destination Session MessageProducer Specific « subscription » TopicConnection Topic TopicSession TopicPublisher ConnectionFactory TopicConnectionFactory Consuming client The code of the consumer is very similar to the preceding code.sun. it is not obligatory any more to implement the MessageDrivenBean interface.provider. "localhost:1099"). we must implement the MessageListener interface.naming. Destination destination = (Destination) ctx.jnp.NamingContextFactory").out. consumer.start().url".enterprise. Connection cnx = connectionFactory.

we use an array of @ActivationConfigProperty specifying the name of the property propertyName and its value propertyValue . The types of properties are based on the Java primitives: boolean .SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 activationConfig = { @ActivationConfigProperty(propertyName = "destinationType". the topic mode makes it possible to use a durable subscription. Indeed. To define the values of the properties it is necessary to use the methods setXxxProperty(Xxx) where Xxx represent the types byte . message. Those are located in the heading of the message. When the destination is of Queue type. we define properties on which we will be able to define criteria of recovery.campus-booster. The selector of message uses the properties of the message as a criterion in the conditional expressions. we define the type of destination destinationType and name JNDI of the destination used ( destination ).aspx?lecture=814&PM=True Page 18 of 100 . the disconnected client lose the messages transmitted during their disconnection. Selector of message It is possible to specify certain criteria allowing not to receive the whole of the messages from a destination.jms. @MessageDriven( activationConfig={ @ActivationConfigProperty(propertyName="subscriptionDurability". we can apply criteria of selection.jms. as we had specified at the beginning of this chapter. the principle of durable subscription does not have any sence.propertyValue="senderType='StockSenderCorp'") These selectors are based on the properties of the messages. You can notice that the development of MDB is really simplified.). @ActivationConfigProperty(propertyName = "destination". All the types of message integrate the methods of reading and writing of properties. The interest is to be able to receive the messages transmitted since the last disconnection. @MessageDriven(activationConfig={ activationConfig= { @ActivationConfigProperty( propertyName = "messageSelector".net/Booster/Pages/lectureSimpleViewer. shorts . We detail his use further. message. Warning The attribute mappedName is not to use because it is not portable between the various server of applications.Topic"). propertyValue = "topic/StockValueTopic")} ) public class StockValueListenerBean implements MessageListener { @Resource private MessageDrivenContext ctx. It is similar to the SessionContext object explained in the part Session Bean. public void onMessage(Message message) { // TODO => update stock value procedure } } All is realizable with the annotations.createTextMessage().. If a problem of connection occurs. these methods are described in the interface javax..setStringProperty("place". The attribute activationConfig allow to configure the properties of the MDB. The type of this object is MessageDrivenContext . However.setText("Les indices boursiers à Paris ont gagné 4% aujourd?hui") ."StockSenderCorp"). propertyValue = "place = 'FR/Paris' and result > 0")} } https://www.we will study the various points of details of these components.. clientId . Thanks to the properties which we have just defined. The methods getXxxProperty() are also proposed to recover the values.propertyValue="Durable") } ) Other properties exist and can be used ( subscriptionName . int .setStringProperty("senderType". In the preceding example. therefore depending of the contents. char . String .setIntProperty("result".. a subscription is NonDurable . TextMessage message = session. The annotation @MessageDriven makes it possible to define the name of the MDB within the container (attribute name). By default.Message (superinterface defining a message). Here an example of use of these selectors of message. @ActivationConfigProperty(propertyName="messageSelector". For that.. Indeed.4). In the following example. the ?durable? factor does not have importance because the messages are automatically stored and must be consumed by a single customer.. and are assigned by the creator of the message. Tolerance of the disconnection to a ?topic? The model of transport of the type ?subscription? obliges the client applications to be connected to the subject (topic) to receive the messages of this one. MessageDrivenContext As the Beans Session. The values taken by this one are: Durable or NonDurable . the Message Driven Beans also have a context of execution of the MessageDrivenContext type. message. By nature for this kind of destination."FR/Paris"). message. Now . The property to be used is subscriptionDurability . It is possible to recover the context of the MDB with the injection (annotation @Resource ). The use of this kind of subscription must be specified on the level of the properties of the MDB. float . These conditions use Boolean expressions in order to determine the messages to receive. Object . propertyValue = "javax. this interface inherits EJBContext and does not add any method.

activationConfig={ @ActivationConfigProperty(propertyName="acknowledgeMode". Let us point out the various steps for sends of a message JMS: Recovery of a ConnectionFactory object Recovery of the destination Opening of a connection Creation of a session Creation of a MessageProducer Creation of a Message https://www. @MessageDriven( name="MyQueue". or not if the transaction fails. One can however disadvise this last value because the supplier could believe that the message was not treated and would decide to transmit it again (what could involve dysfunctions). Other functionalities are possible. <. if the one day result is not located between +10% and 10%. This solution is typically used in our example of forwardings. Let us take the case where we wish to treat in a MDB all the messages having a relationship with the money markets Parisian... the message will continue to be sent. As regards shipper. It allow the client application to warn to the supplier that the message was received. The message of return alerts the system when the object is prepared and dispatched. Moreover. transparent mechanism managed by the supplier and container MDB. message. the cost of sending an acknowledgement of delivery is negligible that it is in capacity of calculation or load network.. the acknowledgements just after the commit. There are two modes of acknowledgement: ?Autoacknowledge? and ?Dupsok acknowledge?. in order to apply different treatments to them. result NOT BETWEEN 10 AND 10 Or treatment of the stock exchange places French or English place LIKE 'FR/%' OR place LIKE 'UK/%' This functionality is useful when we wish to sort and distribute the messages located in the same destination towards various MDB. and francfortoise. @MessageDriven( name="MyQueue". You can use operators AND.propertyValue="Autoacknowledge") } ) @TransactionAttribute(TransactionAttributeType. The mode ?Autoacknowledge? defines that the acknowledgement must be sent as soon as the message was transferred to the MDB.. mappedName = "queue/MyQueue". MDB and JMS client We directed our presentation MDB and JMS mainly towards the consumption of messages more than on the production of these messages. we define the destination of answer in the following way: Destination replyDestination = context.aspx?lecture=814&PM=True Page 19 of 100 .NOT_SUPPORTED) public class MyTopicListener implements MessageListener { // .lookup("queue/ReplyQueue").propertyValue="Dupsokacknowledge") } ) @TransactionAttribute(TransactionAttributeType. The MDB receiving the message can then recover this property and send in its turn a message. } The second solution consists in specifying the JMSReplyTo value in the parameters of heading of the message. London.. Destination replyDestination = message.net/Booster/Pages/lectureSimpleViewer. to warn the investor that this day is not an ordinary one. This mechanism is based on the transactions on the level of the MDB.campus-booster. } For Dupsokacknowledge . The first consists in using acknowledgements of delivery. This method differs from preceding because it allows a real information feedback concerning the treatment of the message. It is difficult for him to know if the message were indeed transmitted (when it wishes to know. Acknowledgement The disadvantage of the asynchronous treatment of messages is that there is no value of return to sender. 'UK/London'. activationConfig={ @ActivationConfigProperty(propertyName="acknowledgeMode". That could not have been implemented with the first solution.. Without this acknowledgement of delivery. the acknowledgement is pushed back at one unspecified moment and the container chooses then the moment when it has few tasks to treat to send it. >. When this one is managed by the container.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION The system is based on the same concepts as the selection of the recordings with SQL. 'GER/Francfort') 17/10/09 18:17 We can also think to an alarm system. mappedName = "queue/MyQueue". OR. That makes it possible to the recipient to send an answer towards the parameterized destination. There exists however many evolutions facilitating the development of the sending of these messages.NOT_SUPPORTED) public class MyTopicListener implements MessageListener { // .getReplyTo(). There are various solutions to this problem. of course). That permit to save the resources.setJMSReplyTo(replyDestination). This solution is also interesting to go up reports/ratios of errors in the business process. place IN ('FR/Paris'.

When the container does not need more the instance. Once the application started.flush(). @Resource (mappedName = "queue/StockAlertQueue") private Queue stockAlertQueue. it calls the methods annotated with @PreDestroy . That generally occurs when the reserve of instances becomes disproportionate compared to the needs or that the application stops. } } public void onMessage(Message message){ try{ //. A MDB is in the state ?Method ready? when the instance is ready to be used. Life cycle Just like the Session Beans. Note The examples presented in this part can completely be implemented within a Bean Session exactly in the same way.. 0). MessageProducer producer = session..aspx?lecture=814&PM=True Page 20 of 100 . we used the annotation @Resource which defines name JNDI of ConnectionFactory and the Destination (of Queue type. @PostConstruct private void connectToFile() { try { fw = new FileWriter(new File("save_topic. are used to release the resources used. The instance is now ready to treat the messages delivered with the listened destination: state ?ready Method?. The code of the method sendAlertMessage (String textAlert) do not changes a lot compared to the implementation code client presented before. The following steps describe the changes of state which a MDB can undergo: The instance is created when the container calls the method newInstance() in the class of the component (generally with the starting of the application). @EJB . Session session = cnx. For that.createConnection(). The second method. These dependences gather the injections annotated with @Resource ..campus-booster. } catch(Exception e) { . A MDB is in the state ?does not exist? when there is not any instance in memory of this one (it was not instanciate yet).txt")) .createTextMessage(). here). the container injects all the dependences of the object. public void sendAlertMessage(String textAlert) { Connection cnx = cnxFactory. producer..SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 Sending of the message Disconnection.net/Booster/Pages/lectureSimpleViewer. the container creates a whole of instance of MDB of which the state is ?ready Method?. cnx.close().send(message). then the container calls the methods annotated with @PostConstruct . } } @PreDestroy private void unconnectToFile() { try { fw.createSession(true. public class StockAlertListener { @Resource (mappedName = "ConnectionFactoryName") private ConnectionFactory cnxFactory. } catch(Exception e) { . } } The first two steps of recovery are automated with the principle of injection.createProducer(stockAlertQueue). like the access to a directory of company or more simply to a file. https://www.close(). message. This type of component has only two states: ?Does not exist? and ?ready Method?. a Message Driven Bean has a cycle of life managed by the container. Then. @PreDestroy .. TextMessage message = session... fw. The interest of the method declared with @PostConstruct is to open a connection towards a service..setText(textAlert). private FileWriter fw = null.

The interest is to be sure that the file is written. The persistent state of the entity is represented by the variables of instance of the class which correspond to the properties of the POJO. If for certain reasons. the address.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 } catch(IOException ex) { ex. A set of standard annotations is defined in EJB 3 specifications. So the creation of an Entity Bean User is summarized with the creation of an User class.printStackTrace().. the sex. such as we would do it in an application Java SE.net/Booster/Pages/lectureSimpleViewer. then the class must implement java. you will have to use the annotation @Table. Note The goal of the default constructor (without argument) is to simplify the instanciation of the class by the container. The dynamic management of any constructor is a heavy task for this one without to be useful. the properties of the class and the class itself should not be final If an instance of the entity have the possibility of being sent to a distant client. is automatically considered as persistent by the container. By default... Persistent fields A persistent field represents a property of Entity Bean. Specification of Entity Bean Class of Bean The Entity Bean class is the first element to be defined in EJB 3. } It is with the annotation @Entity that the container will be able to know which classes must be consider as Entity Bean. The solution was to define a constructor common to all Entity Bean: the default constructor. } Note The name table ?User? is a reserved name in certain databases like PostGreSql.. The default value used is the name of the class (?User? in the preceding example). The methods. Indeed. Like known as previously.campus-booster. of Entity Bean. The class can as well inherit a class entity as a class not entity.. These various concepts will be explained throughout this chapter. it is the abstract diagram of Entity Bean.Serializable. The class must have a constructor without argument which can be public or protected.io. the first name. @Entity(name = "MyUser") public class User { //. Indeed. you want to map on another table. however. catalog (optional): define the catalogue used. This connection is called the mapping. diagram (optional): define the diagram used. } } Notice that we forced the writing in the file at the end of the method onMessage() with FileWriter. comply with certain rules: This class can be abstract or concrete. the date of birth. and conversely. be protected or not specified.flush(). which we will see later. the methods of recall can not be called and the data remained in memory can be lost. Any field (variable of instance) not ?static? and not ?transient?. This name is used to represent the entity in the requests EJBQL. Nevertheless.. @Entity @Table(name = "XUser") public class User { //. EJB 3 Entity Beans support the heritage. This annotation is on the class and allow to define. associations and the polymorphic requests. This attribute is used when the container generates the tables with the deployment and of anything the execution even entity does not affect. Entity Beans are POJO (Plain Old Java Objects ).. the class can have overrided manufacturers if the preceding condition is observed. Entity Bean User is mapped on the table ?User?.. This annotation has various attributes: name (required): defines the name of the table to use for the mapping. uniqueConstraints (optional): defines the constraints which will be placed on the table. The client cannot reach directly the variables and must use the getter and setter or other methods trades of the class. RMI uses the (un)serialisation to pass the arguments between the client application and the client. We can consider two types of annotation related to Mapping Objet/Relationnel : annotations related to the properties https://www. The name used must be unique in an application. For an user entity. it will be for example: the name. for certain reasons.aspx?lecture=814&PM=True Page 21 of 100 . the name of the entity with the attribute name . @Entity public class User { //. } Entity Bean is related to a table in database. therefore we named it in the example above ?XUser?. These variables can be private. This class must.

In our Entity Bean User . scale=2) public float getPrice() { return price.aspx?lecture=814&PM=True Page 22 of 100 . However it is possible to use the default mapping. This one ?ondefine? default values declared by EJB 3 specification. The name of the property is used by default. There are two types of identifier: simple and composite. Primary Key Entity Bean must have a field whose value is unique. optional ( true default) : determines whether the property accepts or not the value " null ". name = "price". it is necessary to annotate this one with @Id . This attribute does not function for the primitive types (which cannot be null ). To specify with the container that a field is a primary key. Other annotations allow to specify the parameter setting of the columns (in the relational table) related to the persistent properties. @Id @GeneratedValue(strategy = GenerationType. The policy of API Persistence is to consider any property as a persistent field. nullable : specify if the column accepts null values or not.LAZY ) or at the time of the loading of the entity ( FetchType. With those. However. and many other properties to be used for a persistent property. Float . the length of the field. the decimal ones (a number with comma) are not used as a primary key. This primary key must be defined only once in all the hierarchy of Entity Bean. table : specify the table used to contain the column. all optional. This mapping will be used when you do not use an annotation for a field (that it is persistent or relational). The container considers by default that the property is annotated with @Basic with the default values of the following attributes: fetch ( FetchType. but use the possibilities exposed about it here to optimize the mapping between its entities and the database. length : specify the length that the data base must associate a field text. can be placed in two ways: Directly on a field On the getter and setter (more precisely on the getter) Default Mapping When you will create your bean.).). in this part the first case the second is more rarely used. insertable : specify if the value must be included during the execution of request SQL INSERT. The length by defect is 255. It is with this attribute that we can specify the SQL type of the column. the String type or Date ( java. The simple types are: primitive types ( int . This attribute is used when Entity Bean is maped with several tables. updatable : specify if the value must be updated during the execution of request SQL UPDATE. This field allow to differentiate each instance from the entity of the others. annotation @Column : name : specify the name of the dependent column.sql. which will be described in a more detailed way in the following parts.EAGER default) : determines whether the contents of the property must be in charge with the request 1 ( FetchType. Double . We explain..net/Booster/Pages/lectureSimpleViewer. double. https://www. The entities using this type for the primary key are likely not portable.EAGER ). Here a description of the attributes.campus-booster. The default number of decimal is defined by the database. Simple Identifier We speaks about simple identifier when this one is composed by a single field whose type is ?simple?. This annotation can be used jointly with the preceding ones. char . This one can quickly test its entities. it is then possible to specify type SQL. @Entity public class User implements Serializable { private int id.. nullable = false.Date or java. a wrapper (For example Integer . The default value is true. it should not remain there. and that corresponds to the annotation @Basic . is true. known as primary key..SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 annotations related to the columns These two types of annotations. This attribute is usable only for the decimal properties (float. } The many default settings of API Persistence offers an advantage to the developer.AUTO) // optionnel public int getId() { return id.. scale : specify the fixed number of figures after the decimal separator (in general the point).Date ).util. float . @Column(updatable = true.. That means that it is not necessary to annotate the properties to indicate them persistent. Note In general.. The default value is the principal table of the entity. precision=5. The annotation @Column will be necessary to use to specify these parameter settings SQL. the primary key is assigned with the field id . The default value columnDefinition : specify the ?piece of code SQL? for the definition of the column in the database. you will need to map the whole of your fields.). unique : specify if the property is a unique key or not (the value is unique in the table). So it is to the manager of persistence selecting the suitable type of variable.

net/Booster/Pages/lectureSimpleViewer. IDENTITY .IDENTITY) public int getId() { /* . @Entity @TableGenerator( name="CONTACT_GEN". For example. IDENTITY type indicates to the supplier persistence assigning the value of the primary key by using the column identity of the data base. Indeed. pkColumnValue="id". Here the detail of the attributes of this one: name : a name for this definition of additional table table : the name of the table in the database pkColumnName : specify the name of the column which identifies the primary key for which the key is generated. Warning The default value for the attribute allocationSize is 50 @Entity @SequenceGenerator( name="SEQ_USER". generator="SEQ_USER") public int getId() { return id. sequenceName (optional): defines the name of the sequence object of the database which will be used to recover initialValue (optional): the value which must start the sequence.persistence. The AUTO type indicates to the supplier persistence using the best strategy (between IDENTITY . That allow to the supplier to use a system of cache in order not to require a new value of each request for new a id.GenerationType .SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 } public void setId(int id) { this. it is preferable to use a field of the entity rather than to add one of them. pkColumnName = "key". This one can be declared on the class or the package with @SequenceGenerator and its attributes: name (require): a unique name for the sequence which can be referred by one or more classes (according to the level used for the declaration of the annotation) the values of the dependent primary keys. sequenceName="SEQ_USER" ) public class User { private int id. SEQUENCE and TABLE . } } The last example uses the annotation @GeneratedValue which allow to indicate to the container to use the best solution for the generation of the primary key. There are four strategies of generation available: AUTO .SEQUENCE. @Id @GeneratedValue(strategy = GenerationType. } } The annotation @TableGenerator allow to specify the parameters of creation of the additional table of generation. obliges the supplier of persistence to use a sequence of the database. allocationSize : the number of incrementings carried out when the supplier requests from the table a new value. */ } The SEQUENCE type. @Id @GeneratedValue(strategy=GenerationType. TABLE . Simple Exemple https://www. the entity Account can contain a property accountNumber which wants to be single by banking logic.campus-booster. SEQUENCE ) according to the data base used. Under MySQL.id = id. allocationSize (optional): defines the number used for the incrementing of the sequence when the supplier of persistence reaches it. it must be used with parsimony. especially for the primary key.aspx?lecture=814&PM=True Page 23 of 100 . as its name indicates it. Even if the automatic incrementing of the primary key relieves the developer. @Id @GeneratedValue(strategy=GenerationType. valueColumnName : specify the name of the column which contains the meter of the primary key. the autogenerated primary key is marked with ? AUTO_INCREMENT ?. This case of use is rarest. Those are defined by the enumeration javax. The TABLE type indicates to the supplier persistence using an additional table to generate the numerical primary keys..TABLE.. } } This type of generation is useful when the database offers a native system of sequence and that it is advised to use it by the supplier of this one. table="GENERATOR_TABLE". This property is then the best candidate for the primary key. The generator AUTO is the type preferred to have a portable application. for example. valueColumnName = "hi". allocationSize=25 ) public class User { private int id. generator="CONTACT_GEN") public int getId() { return id.

java. this type is used) @Entity @Table(name = "COUNTRY") public class Country implements Serializable { private int id.AUTO) public int getId() { return id. public Country() { } @Id(generate = GeneratorType. One to One A relation "One to One" is used to bind two indissociable uniques entities. @Entity public class AccountInfo { private int id. "Many to One".util. A relation is known as oneway if only one part knows the relation.util.io.campus-booster. They are these relations between entity EJB 3 which we detail in the next parts. It implements java. } } 17/10/09 18:17 Relations We saw the definition of persistent property previously. it is described as bidirectional if the two parts know it. private String name.net/Booster/Pages/lectureSimpleViewer.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Here an example of simple POJO. To associate two entities with this type of relation.Set . private String cardNumber. } public void setId(int id) { https://www. It allow to define the structure of table " COUNTRY ". On the other hand. We speak then about relations between entities. } public void setName(String name) { this. is multivalued ("One to Many". The other annotations are not obligatory allow to specify more precisely various parameters: @Table defines the name of the table to be used @Basic defines the type of a persistent field (by defect. @Id @GeneratedValue(strategy=GenerationType. We will suppose. It proves that an entity generally does not work only but that it is connected to other entities. it is enough to create a property whose type is an entity (cardinality 1) or a whole of entity (cardinality N).util. } public void setId(int id) { this. in our example.Map . considering previously. and java.id = id. mappedBy : specify the field owner of the relation the case of a bidirectional relation. For the relations where one side. targetEntity : specify the class of a target entity. java. This one takes again the attributes of @Basic . a body has one heart. GeneratorType. private double amount. private String accountId.AUTO defines a key incremented car). "Many to Many"). which a user User has one AccountInfo account. the annotation @OneToOne should be used. at least. the types of containers available are: java. } public String getName() { return name.AUTO) @Basic public int getId() { return id. For example. and proposes other optional attributes: cascade : specify the operations to be carried out in cascade.name = name.aspx?lecture=814&PM=True Page 24 of 100 . or a person has only one indentity card. Here the example of the oneway relation between User and AccountInfo with this method.Serializable in order to be able to be sent directly to a distant client (and thus to pass through a network). To define a relational field within an entity. This type of relation can be mapped with 3 manners in the database. The obligatory annotations are: @Entity which declares the class as being an entity @Id which declares the primary key (generate allow to define the type of generation to be used for this key. The first solution consists in using the same values for the primary keys of the two entities.util.List .Collection . It is then necessary to specify this choice via the annotation @PrimaryKeyJoinColumn (joint by primary key). This attribute is not used a lot because the annotation uses the type of the property automatically.

.. @Entity public class User { // . The annotation to use is @JoinColumn. unique=true).. inverseJoinColumns = @JoinColumns(name="accountinfo_fk". } The attribute mappedBy declares that the side owner is that holding the property accountInfo . } // .. @OneToOne @JoinColumn(name="account_id".. } } @Entity public class AccountInfo { //..campus-booster. here. @OneToOne @PrimaryKeyJoinColumn public AccountInfo getAccountInfo() { return accountInfo. @Entity public class AccountInfo { // . } // Others getters and setters } @Entity public class User { // .. private User user.id = id.. However. @Entity public class User { // .. the multiplicity ? One to One? is respected if and only if one unique constraint is defined on each foreign key..net/Booster/Pages/lectureSimpleViewer. The last solution consists in using a table of association of the links between the two entities. } // .SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 this.. it is possible to find it in an existing system which one wishes to make evolve. It is thus. However. } public String getCardNumber() { return cardNumber. } The second solution consists in using a foreign key on a side of the relation.. referencedColumnName="id") public AccountInfo getAccountInfo() { return accountInfo. unique=true) ) public AccountInfo getAccountInfo() { // .. @OneToOne(mappedBy = "accountInfo") public User getUser() { return user. It makes it possible to parameterize the column of joint to be used.. @OneToOne @JoinTable(name = "UserAccountInfo" joinColumns = @JoinColumn(name="user_fk". @OneToOne(mappedBy = "accountInfo") public User getUser() { https://www.aspx?lecture=814&PM=True Page 25 of 100 ... it should be noted that the column of this key must be marked like single in order to simulating correctly the relation ?One to One?.. the User entity which holds the relation and thus has the capacity to bind a user on an account (the reverse being impossible). } public void setCardNumber(String cardNumber) { this. private int id. } // ... Even if this case is rarer. This one makes it possible to specify the name of the column referred by the foreign key of association.cardNumber = cardNumber. } The annotation @JoinColumn resembles @Column but has an optional additional attribute: referencedColumnName . The example shows the bidirectional relation.

net/Booster/Pages/lectureSimpleViewer. uniqueConstraints : specify the unique constraints to place in the table. private User user. declare a property multivalued Collection<Portfolio> portfolios . } public void setUser(User user) { this. For example.. but a bank account belongs only to only one person. An article can be associated several categories (cardinality N) and a category can gather several articles (cardinality m). generation of the table is activated. This attribute is used only if the In the absence of any parameter of the annotation @OneToOne . the link between the two entities will be made with a column of joint (second solution) in the owner entity.. we will not return above. the name would be accountInfo_id . } } The entity Portfolio . In our following examples.portfolios = portfolios. Concretely.aspx?lecture=814&PM=True Page 26 of 100 . inverseJoinColumns : specify the columns (together @JoinColumn ) of the joint table which refer the primary key(s) of the entity not owner (opposite side). In the case of a bidirectional relation.. It is however a considerable case when we use of an existing data source. the entity User . An association ?Many To One? is defined on a property with the annotation @ManyToOne . Here a description of the attributes of this one: name : specify the name of the joint table catalog : specify the catalogue of the joint table schema : specify the diagram of the joint table joinColumns : specify the columns (together @JoinColumn) of the join table which refer the primary keys of the entity owner of the relation (side owner).campus-booster. For that. In relational term. } } This technique obliges to write more lines. the owner entity User definite the named persistent property accountInfo . @ManyToOne @JoinColumn(name = "user_fk") public User getUser() { return user. } } @Entity public class User implements Serializable { //. If you do not wish to use them. a user can have several wallets of actions. this relation imposes the use of a table of association.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 // . private Collection<Portfolio> portfolios. The annotation @JoinTable allow to configure the table of joint for relation. Notice the use of the credits which avoid defining the target entity in the definition of our relation.. The name of this one will be the result of the concatenation of the name of the relational property with the name of the primary key of the other entity. is used to bind to a unique instance of an entity A. @OneToMany(mappedBy = "user") public Collection<Portfolio> getPortfolios() { return portfolios. In the same way that with a relation ?One to One?. then you will have to specify the target of your relation with the attribute targetEntity of the annotation @OneToMany . it is enough to use multivalued properties on each side of the relation (if this one is bidirectional) and to annotate them with @ManyToMany . being the part of the relation having a cardinality of 1. @Entity public class User { https://www. The way of proceeding already having been explained previously. it is possible to use a table of association. Many To Many The last type of relation available is ?Many to Many?. The attributes of these two annotations correspond to those of the annotation @OneToOne . On the other hand. It can be used to bind instances of two entities between them.user = user. @Entity public class Portfolio { //. the primary key of AccountInfo being id . between articles and categories.. and respectively ?Many To One?. in the example used previously. the other side must use the annotation @OneToMany .. but a wallet is dependent only on one user. a person has several bank accounts. part of the relation to cardinality ?N?. a group of authorities of an entity B. defines a User property user . For example. One To Many and Many To One A relation ?One To Many?. } public void setPortfolios(Collection<Portfolio> portfolios) { this. without to increase the performances.

. For example. a too important use of this mechanism can very quickly harm the performances of the application.aspx?lecture=814&PM=True Page 27 of 100 . the CascadeType. For example. each User user has a whole of hobbies Hobby. when a user is removed.REMOVE type can be applied only to associations "One to One" or "One to Many". } public void setHobbies(Collection<Hobby> hobbies) { this. } The use of the mechanism of cascade is a real simplification for the developer. modification.net/Booster/Pages/lectureSimpleViewer. @ManyToOne and @ManyToMany have the attribute cascade .MERGE : automate the recording of the modifications of the entities related to marked association. @ManyToMany @JoinTable(name = "USER_HOBBIES". reloading. There are 4 possible operations on the entities: addition. CascadeType. private Collection<User> users.campus-booster. on the relation between User and Portfolio. each hobby Hobby can be related to several User users. referencedColumnName = "id") ) public Collection<Hobby> getHobbies() { return hobbies. joinColumns = @JoinColumn(name = "user_id". Here the code corresponding: @OneToMany( cascade = { CascadeType. } public void setUsers(Collection<User> users) { this. This one specifies the operations to be carried out in cascade. Indeed. } } Here. Indeed. These operations are gathered in the CascadeType enumeration.REFRESH : automate recharging (side bases data) entities related to marked association. And conversely. it does not have to manage the loops of suppression any more. this tool must be used judiciously and with parsimony. The cascade means that operation applied to an entity is propagated with the relations of this one.. the relation ?One to One? between User and AccountInfo obliges to safeguard. } } @Entity public class Hobby { //. CascadeType..SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 //. update and destroy AccountInfo when these operations are carried out on the instanct of User corresponding.PERSIST : automate the recording of the entities related to the association marked during the recording of the entity owner (method persist() ).. referencedColumnName = "id"). CascadeType..PERSIST }. Warning According to the specification. private Collection<Hobby> hobbies. suppression. } In the same way.users = users. it is logical to record or remove the wallets when the user is respectively recorded or removed.ALL : cumulate the 4 types of cascade. modification. Here the code corresponding: @OneToOne(cascade = CascadeType. CascadeType. The use of this type for other associations is not portable. during the recording of the modifications of the entity owner (method merge() ). during the recharging of the entity owner (method refresh() ). CascadeType. Relationnal sample This bean integrates a relation with another bean of the type: ManyToOne. @ManyToMany(mappedBy="hobbies") public Collection<User> getUsers() { return users.hobbies = hobbies.REMOVE : automate the suppression of the entities related to marked association. inverseJoinColumns = @JoinColumn(name = "hobby_id". This relation highlights a field of the Country type..ALL) @PrimaryKeyJoinColumn public AccountInfo getAccountInfo() { return accountInfo.REMOVE. during the suppression of the entity owner (method remove() ). mappedBy = "user" ) public Collection<Portfolio> getPortfolios() { return portfolios. The use of the relational annotations describes more in detail the relation: @ManyToOne defines the type of the relation (ManyToOne) @JoinColumn defines the column of joint for this relation https://www. its account is also. @OneToMany . However. Cascading operations The annotations @OneToOne . CascadeType.

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION

17/10/09 18:17

package com.society.stockmanager3.entities.beans; import import import import import import import java.io.Serializable; javax.persistence.Entity; javax.persistence.GeneratorType; javax.persistence.Id; javax.persistence.JoinColumn; javax.persistence.ManyToOne; javax.persistence.Table;

@Entity @Table(name = "CITY") public class City implements Serializable { protected int id; protected String name; protected Country country; public City() { } public City(String name) { this.name = name; } @Id(generate = GeneratorType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } @ManyToOne(optional = false) @JoinColumn(name = "countryId") public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

One Many to Many or two One to Many ? A relation ?Many to Many? is the regrouping of two relations ?One to Many?. Indeed, the relation ?Many to Many? uses a simple table of joint containing the primary keys on the two sides of the relation. What happen if we wish to add properties to this relation? For example, when an order gathers products, those can also be used in several orders. We then find ourselves in the case of a relation ?Many to Many?. However, it is generally useful to add a property concerning, for example, the quantity of the desired product. The use of the annotation @ManyToMany does not allow the insertion of additional properties the relation between the two objects. It is then necessary to use a double connection ?One to Many? and intermediate Entity Bean. In our example, we have Entity Bean following: Order , Product and OrderLine , respectively representing an order, a product and the lines of the orders. Here respective codes:
@Entity @Table(name="ORDERS") public class Order { private int id; private Date orderDate; private Collection<OrderLine> orderLines; @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } @OneToMany(mappedBy = "order", cascade = {CascadeType.REMOVE}) public Collection<OrderLine> getOrderLines() { return orderLines; }

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 28 of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION

17/10/09 18:17

public void setOrderLines(Collection<OrderLine> ol) { this.orderLines = ol; } } @Entity public class Product { private int id; private String name; @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

The classes Order and Product are Entity Bean as we could describe them in the first parts. Entity Bean OrderLine is the central point of the relation. It gets the two properties product and order respectively related to Entity Bean Product and Order . Moreover, if an autogenerated unique primary key would simplify the work of the developer, it is more judicious to work with a composite primary key. Indeed, the regrouping of the primary keys of Product and Order are a good candidate for a primary key, since an order cannot have the same product twice (in this case there it is enough to increment the quantity). We must then create a OrderLinePk class to define this composite primary key. This one contains two properties orderId and productId respectively representing the id of Order and Product . The annotation @Embeddable declared below makes it possible to declare an entity in time that key composite primary education.
@Embeddable public class OrderLinePk implements Serializable { private static final long serialVersionUID = 1L; private int orderId; private int productId; protected OrderLinePk() { } public OrderLinePk(int orderId, int productId) { this.orderId = orderId; this.productId = productId; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public int hashCode() { return orderId ^ productId; } public boolean equals(Object that) { return (that instanceOf OrderLinkPk && orderId == productId); } }

Why we use the methods hashCode() and equals() above? They are used for calculter a value based on the contents of the instance and to compare this one with others.
@Entity @IdClass(OrderLinePk.class) public class OrderLine { private Product product; private Order order; private int quantity;

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 29 of 100

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION

17/10/09 18:17

public OrderLine() { } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @ManyToOne @JoinColumn(name="orderId", optional=false, insertable=false, updatable=false ) public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } @ManyToOne @JoinColumn(name="productId", optional=false, insertable=false, updatable=false ) public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } @Id public int getProductId() { return getProduct().getId(); } @Id public int getOrderId() { return getOrder().getId(); } public void setOrderId(int orderId) { getOrder().setId(orderId); } public void setProductId(int productId) { getProduct().setId(productId); } }

We use the annotation @IdClass in order to specify the class of the primary key used. The getters getProductId() and getOrderId() ondefine those of the OrderLinePk class. However, they respectively turn over the primary key of the dependent order Order and that of the dependent product Product . That raises a problem: the columns orderId and productId are already used to refer in the relations Many to One. They are used at the same time as primary key and foreign key! The supplier of entities encounters a problem: to assign the primary key and the foreign keys. To specify that we do not wish to assign the foreign keys automatically, it is necessary to assign the value false to the attributes insertable and updatable of the annotation @JoinColumn . The heritage Here 3 possible relational types of mappings: A single table by hierarchy of class. A table by concrete class. A separation of the specific fields of a class girl in a separate table of the table relationship. A junction is then made for instancier the class girl. The examples of this part will use two Entity Bean: Bond and Stock which inherit both Entity Bean FinancialProduct (abstract class).

Warning
Only one primary key must be defined in a hierarchy. Here, the primary key is in the root class FinancialProduct .

https://www.campus-booster.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True

Page 30 of 100

and ?Stock? if its type is Stock . columnDefinition : SQL fragment to be used for the declaration of the column (used during the generation of the tables by the container).. } @Basic public int getMonthDuration(){ return monthDuration. // nombre de mois que dure l?obligation //. we will study the annotations used and the generated relational structure. length=10 ) public abstract class FinancialProduct { private int id. CHAR and STRING . However. The goal is to give you the elements enabling you to make the best choice according to various situations'. To define a heritage using the strategy "unique table". length : size of the column for the discriminator at the root of the string. A table for a hierarchie of class In this strategy. because no joint is carried out. For each case. discriminatorType=DiscriminatorType.aspx?lecture=814&PM=True Page 31 of 100 ..SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 We will describe the possibilities of each one of these configurations. Possible values are INTEGER .. the contents of the discriminatory column contain ?Bond? if the stored EntityBean is of Bond type. @Entity @DiscriminatorValue("BOND") // valeur par défaut public class Bond extends FinancialProduct { private double rate. } //. the data use more place because the whole of the columns is not always used (according to the type of recorded data). The type of heritage used is specified on the level of root Entity Bean by the annotation @Inheritance ..campus-booster. It is necessary to use the annotation @DiscriminatorColumn to specify the details of this column. However.. } The only attribute of this annotation is strategy .. //. } //. it is the value InheritanceType. rate has a https://www. The attributes of this annotation are: name : name of the column of discrimination discriminatorType : discriminator class to be used defined by the enumeration. The concrete children classes can specify the discriminatory value with the annotation @DiscriminatorValue . The default value of a discriminator of the type STRING contains the name of the class of Entity Bean. // taux de rendement de l?obligation private int monthDuration. Thus.AUTO) public int getId(){ return id.. } Here the result at the database level (one table for two entities): This strategy provides an important profit of performance..SINGLE_TABLE which will be used.net/Booster/Pages/lectureSimpleViewer. } @Entity @DiscriminatorValue("STOCKOPTION") public class Stock extends FinancialProduct { // . all the classes of the hierarchy are mapped in same and unique table. @Id @GeneratedValue(strategy=GeneratorType.STRING. Here. the supplier uses a specific method to generate automatically a value for Entity Bean. @Entity @Inheritance(strategy=InheritanceType. For the other types of discriminator. @Basic public double getRate(){ return rate.SINGLE_TABLE) @DiscriminatorColumn( name="financialproduct_type".. like their advantages and disadvantages.. this strategy requires a column allowing to differentiate the types of entity of the hierarchy. It allow to specify the type of strategy to use with the InheritanceType enumeration.

aspx?lecture=814&PM=True Page 32 of 100 . The main disadvantage is the heaviness of the polymorphic requests (selection on the whole of FinancialProduct. that means that the table ? FinancialProduct ? is not created nor not used. each one of these tables integrating the properties defined in FinancialProduct . Each children class is related to its own separate table containing the specific properties of that one. the selection of a concrete type (here Bond or Stock ) is optimized. The link between the tables ?child? and the table root is made with the primary keys. } Here is the result in the database: The major advantage of this configuration is during insertion because the addition is made only in one table.TABLE_PER_CLASS) public abstract class FinancialProduct { //. } Here the result at the database level (place optimization tacken by the data): https://www.... DataBase Administrators never appreciate this kind of practice. is related to a recording of the table ?FinancialProduct? having value 15 for the primary key.. it is necessary to specify the strategy defined by InheritanceType. for example). } @Entity public class Stock extends FinancialProduct { //. In this case.. That means that all the properties of the class (including the inherited properties) are included in the table related to this entity. In the same way. a recording of the table ?Stock? or ?Bond? whose value of the primary key is 15. Concretely. Indeed. @Entity @Inheritance (strategy=InheritanceType. One table for a specific part of data In this last strategy. each concrete class Entity Bean is related to its own table.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION value ?null? when the recording corresponds to a Stock Entity Bean. the data base must use instruction SQL ?UNION? in order to gather the recordings located in the two tables... SELECT relates to only one table.campus-booster. Indeed. One table by concrete class 17/10/09 18:17 The second strategy presented here is ?one table by concrete class?. Entity Bean Stock and Bond which inherit the FinancialProduct class are mapped respectively on the tables ? Stock ? and ? Jump ?.JOINED) public class FinancialProduct { //. Indeed.. the class root of the entities is represented by a table.net/Booster/Pages/lectureSimpleViewer. on our example. the primary key of the class girl is related to that of the class relationship.. } The children classes Bond and Stock do not need another annotation only @Entity : @Entity public class Bond extends FinancialProduct { //. @Entity public class Stock extends FinancialProduct { //. To specify this strategy. } The children classes Bond and Stock have simply to inherit FinancialProduct . The heritage is declared here with the InheritanceType.JOINED strategy.. The other disadvantage is the duplication of the columns in each table of Entity Bean.TABLE_PER_CLASS for the annotation @Inheritance . Thus. @Entity @Inheritance (strategy=InheritanceType.

used in our example: <?xml version="1.EntityManagerFactoryProvider KODO: kodo. when the client wishes to recover all Entity Beans of the FinancialProduct type.spi. It is the « ideal » model for the dBa (not of loss of memory because all the fields are used.EntityManagerFactoryProvider GlassFish (Sun Application Server 9) uses TopLink: oracle.ejb. use the default supplier of the server of application: JBoss uses Hibernate: org.campus-booster.toplink. Summary of the methods of mapping of the heritage Here a summary of the advantages an disadvantages of the differents strategies: Table 6.essentials. Here the file ?persistence. the GlassFish presistence provider.cm p3.).PersistenceProviderImpl https://www.HibernatePersistence Oracle Application Server uses TopLink: oracle.. <jtadatasource> (01) : allows to define name JNDI for the data source to use.hbm2ddl.. Advantages and disadvantages of the differents mapping strategies Strategy Advantages Disadvantages SINGLE_TABLE No joint. therefore lowers performance Persistence unit The persistence unit is a device making it possible to establish a link between Entity Beans and the database Configuration of a persistance unit The specification defines a file which gathers the whole of information of persistence. The name is used to identify the unit of persistence during its use with the annotations You will have to define several units of persistence if you wish to use several data sources. ?.dialect.0"> <persistenceunit name="stockmanagerUP"> <jtadatasource>java:StockMainDS</jtadatasource> <provider>org. This file will be read by EJB container during the deployment of the application.MySQLInnoDBDialect" /> </properties> </persistenceunit> </persistence> Here a description of each mark used: <persistenceunit> (0N) : declare a unit of persistence The attribute name assigns a unique name to this unit in your application.hibernate. Each unit of persistence uses a unqiue supplier. This one must be parameterized on the server and integrate the Transactions.xml? and to place this file in repertory ?META INF?.ejb.persistence. the container will not associate any context of persistence in the application.0"?> <persistence version="1..auto" value="createdrop" /> <property name="hibernate.ejb.hibernate.ejb.hibernate. generated request SQL will result in a simple ? SELECT * FROM FinancialProduct. However.dialect" value="org. to the root of the project. Warning You must name correctly the file ?persistence. in environment Java EE.HibernatePersistence</provider> <properties> <property name="hibernate.toplink. Warning Toplink..net/Booster/Pages/lectureSimpleViewer. But is also to provide a good support of polymorphism. the disadvantage is that it requires the use of several joints between the tables during recovery of data. <provider> (01) : allows to define the class of implementation of the supplier of persistence used in the application (subclass of javax. therefore very powerful Nonoptimal organization of the data TABLE_PER_CLASS Powerful in insertion Heavy polymorphism to manage JOINED Integration of the data close to the model object Intensive use of the joints.persistence.aspx?lecture=814&PM=True Page 33 of 100 . The container then creates an instance of the supplier of persistence with the required parameters. In the case of important hierarchies (great depth of the heritage) that can involve bad performances.cm p3.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 The advantage of this strategy is to have a clearly relational model. parameterized with Hibernate. Thus. You must name this file: ? persistence.xml?. If the name does not match.xml?.essentials. You can.PersistenceProvider). doesn't supports the joined inheritance type..

unitName : the name of the unit of persistence defines to use to inject EntityManager. This one does not apply that to entities yet not recorded in the database.SQLServerDialect org. } The context of persistence is created at the same time as the Bean Session and has the same cycle of life as this one.xml?. modification and suppression (defined by acronym CRUD: Create Read Update Delete).hbm2ddl.dialect : Table 7.hibernate.MySQLInnoDBDialect Persistence manager We will describe. as one can see it in the package org.PostgreSQLDialect org. The diagram will be generated according to the annotations read in the classes of entities.hibernate. is injected. The application uses a whole of systems without really being aware of it and having the difficulties of use which each system can induce. https://www.dialect parameter the dialect used by Hibernate to communicate with the data base (here MySQL).hibernate.hibernate.aspx?lecture=814&PM=True Page 34 of 100 .hibernate. with Entity Manager. This method is undoubtedly simplest and most practical.net/Booster/Pages/lectureSimpleViewer. There are some for the majority of the databases available. @Stateless @Local({CommonService. related to the unit of named persistence stockmanagerUP . reading.dialect.hibernate.auto with the value update .dialect.dialect. This one allow automatically to generate the diagram of the database but also to update it in the event of modification of the structure of Entity Bean.hibernate. in this part.dialect. A <property> is defined by a name (attribute name ) and a value (attribute value ). It is what will be presented in the examples of the following parts.persist(Object o) .DB2Dialect MySQL (Inno DB) org. This operation results in the call of the method EntityManager. This mark gathers the whole of the properties <property>. the use of API EntityManager in order to manage the cycle of life of an instance of Entity Bean. This annotation admits several attributes: name : declare a name local referred on a unit of deployed persistence (local reference towards a unit of persistence).dialect. You must annotate the variable of instance of the type EntityManagerFactory or EntityManager with @PersistenceContext. Here. Like theses units of persistence use Hibernate. the handling of the data with a container EJB is carried out by defining a Bean Session in "facade". This Beans Session reaches the context of persistence and can then work with the instances of Entity Beans. Note The access to the data is represented by the operations of addition. Persist an entity instance To record an entity mean to insert it in the database.DerbyDialect org. In a default environment Java EE. We must specify the property hibernate. The property hibernate.HSQLDialect org.hibernate. During all the life of the Bean Session. List of majors dialects proposed by Hibernate Database PostGreSQL Oracle SQL Server HSQLDB Derby DB2 Class of dialect org. EntityManagerFactory . Note The design pattern "facade" provides a uniform interface of access to a whole of subsystems. the container analyze the whole of the classes of the JAR file containing the file ?persistence.dialect. type : indicate the context type of persistence injected ( EXTENDED or TRANSACTION ).class}) public class CommonServiceBean implements CommonService { @PersistenceContext(unitName="stockmanagerUP") protected EntityManagerFactory emStockManagerFactory. Recovery of Entity Manager It is possible to let the container give the responsability to inject an instance of Entity Manager at the time of instanciation of the Bean Session. It is closed when the Bean Session is destroyed.dialect. A unit of persistence is mapped with a whole of Entity Bean. we can parameterize the engine of persistence with the properties available (related to Hibernate). We generally implements Pattern DAO to standardize these accesses In the majority of the cases. Here an example of use within the business application of wallet of actions.campus-booster.OracleDialect org.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION <properties> (0N) : This mark allow you to configure the attributes of configuration of the supplier of 17/10/09 18:17 persistence. the instance of Entity Beans associated with the context of persistence are managed.

it is important to be able to recover them. User newUser = new User(). Finally. you must first of all create an instance.findUser(2). From there. newUser. entityManager. However differences exist. It is not possible to call the method persist() apart from a transaction only if Entity Manager is of wide type ( EXTENDED ).persist(newUser). userId)..find(User. If the customer application wishes to record the modifications made locally. 1). That depends on the mode used for synchronization at the data base. the modifications will be synchronized automatically. String email) { User currentUser = entityManager. newUser. currentUser.setFirstname("Cyril"). https://www. public void changeUserEmail(int userId. There are two ways of recovering these objects of the database.class. if (user1 == null) { // .aspx?lecture=814&PM=True Page 35 of 100 . We will detail the recovery of objects starting from their primary key. It is the case. } Modify entities There are two ways of modifying an entity. Entity Manager must be associated to the current transaction if it is wished that the modifications be recorded.find(User.campus-booster. it must return the authority to the Bean Session. Entity Manager proposes the following method: <T> T find(Class<T> entity. It also initializes the basic states of the lazyloading associated the properties.merge() in order to attach the instance to the context of persistence.com"). The other solution is to use when you wish to amalgamate the modifications made on an object detached towards the context of persistence. } The context of persistence is closed after the execution of the method findUser() (we suppose that the Bean Session uses management of the transactions).setEmail("popom@supinfo. public User findUser(int userId) { return em. Those are really affected in database when the transaction finishes or that the method flush() is called explicitly.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 To record an entity. Either to load it from the database and the modifications within the transaction or you apply you to him wish to update a detached object and in this case there you must use the method merge() . then to affect its properties and its relationships to the desired values. } In the preceding example. You can then change the properties of this instance. this one become managed until the closing of the context of persistence. Recovery entities Once the objects are saved. Let us imagine that a rich client calls the method findUser() following: @PersistenceContext private EntityManager em. returned instance is detached and the modifications applied are not synchronized any more. it is enough to call you the method persist() . If the method persist() is called in a transaction. for example. When you recover an entity with find() or with a request. User user1 = entityManager. the instance newUser becomes managed and its insertion in database is put in the queue of Entity Manager. insertion in data base can be immediately made or put in queue until the transaction finishes. We will not have time to describe this operating mode more..find(User.net/Booster/Pages/lectureSimpleViewer. The method find() return null if no entity is associated with the required primary key.setEmail(email). User returnedUser = adminService. userId). as you can do it with a Java object.class.class. The other solution consists in working with requests EJBQL (see the following chapter). You must use the method EntityManager. when an entity leaves container EJB towards another application (Web or rich Customer). Once this method called. Object primaryKey) The use of the generics avoids having to cast the return value.

?managed? : mean that the instance has an identity associated with the persistent context.com"). @PersistenceContext private EntityManager em. user. adminService. Warning flush() and commit() are two different operations! flush() sends requests SQL to the data sources whereas commit() validates the transaction on the level of these sources.. the method updateUser() must use EntityManager. } Various behaviors apply according to the context in which you call the method merge() . If Entity Manager holds already an instance of the entity having the same primary key. This state results from the instanciation of Entity Bean with new.find(userId).remove(userToRemove). it is possible to cancel the suppression. This operation override all the modifications which could be made to the entity.campus-booster. This copy is then attached to the context of persistence and the modifications made above are synchronized with the data base. It is generally the case when the instance is initialized in the container then sent to another third (presentation. @PersistenceContext private EntityManager em. public void workOnUser(int userId) { User user = em.com").refresh() in order to reload the entity since the data base.find(userId). you can use the method EntityManager. In this case there.refresh(user). public void updateUser(User user) { User attachedUser = em.setEmail("nomail@supinfo. However. the developer can force synchronization by explicitly calling the method flush() of Entity Manager. An instance is generally in this state when it comes to be recorded. } The call to the method remove() detaches the entity of the context of persistence. Reload entities If you know that the instance of an entity does not reflect the values of the database . This is why the developer must work with the instance turned over by the method merge() if it must make other modifications on the entity. To cancel this suppression (in the same context of persistence) it is necessary to call the method persist() in order to attach the instance to the context. Synchronization with database When you call the methods persist() .updateUser(returnedUser). then it creates a complete copy of the object passed in argument and return it.net/Booster/Pages/lectureSimpleViewer. the parameter user of the method updateUser() remains detached and is not synchronized with the database. Meanwhile. Management of the cycle of life of an entity The cycle of life of an instance of Entity Bean includes 4 distinct states which it is necessary to know and understand.merge() in order to attach the instance to the context. the changes are not synchronized immediately.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 returnedUser. Delete an instance The EntityManager. em. This synchronization is established automatically at the end of a transaction or when Entity Manager decides to empty its queue. Here a description of these various states: ?new? : mean that the instance isn?t associated to a persistent context. modified or to be recovered. em. merge() or remove() . the email is not modified because of the call to the method refresh() . Web. @PersistenceContext private EntityManager em.merge(user). https://www. We speak about "request" because the suppression is not effective immediately but only with the call of the method flush() or at the closing of the context of persistence.setEmail("nouvelleemail@supinfo.). ?detached? : mean that the instance is not associated any more with the persistent context from where it comes. } In the last example.remove() method is used to ask for the suppression of an entity of the database.aspx?lecture=814&PM=True Page 36 of 100 . If Entity Manager does not contain an instance of the entity with the same primary key. In both cases.. then the contents of the parameter (user here) are copied in the attached instance. public void removeUser(int userId) { User userToRemove = em.

EJBQL makes it possible to use the objects of Entity Beans of the application directly in the requests.find(User. First of all.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION ?removed? : mean that the instance has an identity associated with a persistent context but which it is intended to be withdrawn from the data base. For example. https://www. it will be impossible to reach the property apart from the container To resolve that. the diagram abstracted owing to lack of Entity Bean. One can then specify the name of reference by the attribute name of the annotation @Entity . one generally uses the annotations. defined by the class To use. if the collection were not charged in the container with EJB. The abstract diagram In order to work with the entities. In a relational data base. which offers. Indeed.class. In this example. the possibility of carrying out requests of the INSERT type. the marked collections ?lazy? are not charged by the container. With specification EJB 3. the name of the class of Entity Bean will be used. For that. In EJBQL you work with the abstract diagrams and not with the name of the tables of your physical diagram. in the case of a detached entity. However. it is necessary to use key word FETCH JOIN in the request (see the following chapter). 17/10/09 18:17 The call of the methods related to the cycle of life is carried out by the container. Indeed. the study of these methods would leave of the framework of this essence. we should be sure that all the properties of the entity used at the customer are initialized before the object is detached from the context of persistence. user. the physical diagram corresponds to the structure of the tables and columns. For that. In the same way.getPortfolios(). it is enough to ask the loading of the data when the entity is still managed. We speaksabout callback methods (methods of return). UPDATE or DELETE.aspx?lecture=814&PM=True Page 37 of 100 .size().campus-booster. the loading of the property cvContent is carried out at the same time than the access to this one. Integrated into system EJB. the loading of the collection is launched at the same time than the call to the method size() of this one. The abstract term distinguishes this diagram from the physical diagram of the data base. The finality of this language is to some extent identical to that of the manager of persistence. indeed. EJB-QL What EJBQL? EJBQL (Undertaken JavaBean Query Language) is a specification of query language.net/Booster/Pages/lectureSimpleViewer.. one usually assimilates it in the name of Entity Bean. However. it?s the portability which enables him to be used with identical between the various versions of language SQL. is ?To use?. } By defect. Warning The dynamic loading functions only on one managed entity ! Another solution consists in using requests EJBQL with explicit joints to recover the already initialized entities.getCVContent(). userId). In the same way. user. this query language has several advantages.. for more facility. In addition. @Entity(name = "AccountInfo") public class AccountInfo { // . this one rests on an abstraction of language SQL and is translated into ?true? SQL at the time of its execution. Detached entities It is necessary to handle carefully the persistent fields marked by ?fetch=LAZY? when Entity Bean is handled apart from the context of persistence. as represents it the following diagram. the supplier of persistence will translate these requests into ?true? SQL at the time of the execution. The abstract diagram is an internal representation of the entities and their relations. But. User user = entityManager. even if this term seems complex at first sight. EJBQL is based on the abstract diagram of Entity Bean.

id = 5 Correspondence in SQL : select portfolio0_. Fundamental of the language A request EJBQL can fill a task of selection (SELECT). in order to recover the user having a wallet of actions.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 Note We advise you to draw a sketch of the diagram abstracted before writing your requests.user_fk = ? It is guessed rather clearly that the use of ". According to the salesmen.name as name38 _. for (User U: allUsers) { // Work on the user. Query query = entityManager. others could be added.getUser() Warning Character of termination " . Double. with the following clauses: SELECT: list Entity Beans and the properties turned over by the request. as we will see it. In this last case. Requests SELECT The most used request is undoubtedly SELECT. the request of research.. portfolio0_. one can represent navigation in the following way: SELECT portfolio FROM Portfolio AS portfolio WHERE portfolio. Integer. In short. Writing of requests Before returning in the innumerable details of this language. It is possible to specify Java types as well there having their equivalent in the data bases (String. at the time of the passage in native request. WHERE: allows to apply search criteria.user_fk as user3_38 _ from Portfolio portfolio0 _ where portfolio0_..user.id as id38 _.net/Booster/Pages/lectureSimpleViewer. it is possible to journalize (?logs?) requests SQL carried out by the manager of persistence. but those are quasi systematically used to recover data. Of course. For example.show_sql? with the value ?true? if you use the engine of Hibernate persistence.resultList(). FROM: Entity Beans defines used. For example. portfolio0. } The preceding example uses three different concepts: Language EJB-QL Entity manager API Query This one turns over the whole of the authorities of Entity Bean User in a list. This one can then be traversed by a foreach.." is similar. A request EJBQL is similar with SQL.createQuery(queryString). The instruction to be used is SELECT like illustrates it the following example.campus-booster. List<User > allUsers = query.) but also Entity Beans. where all the users are selected: https://www. modification (UPDATE) or suppression (DELETE).aspx?lecture=814&PM=True Page 38 of 100 ." is used to sail between the properties and the relations of Entity Beans. "of requests SQL does not have to be used. We will try to the maximum to illustrate the requests of example with their correspondence SQL. the criterion will apply to the primary key. String queryString = "SELECT user FROM User AS user". used by EJBQL to sail between the persistent and relational properties. it is enough to add the property ?hibernate. The details of use of these elements are explained throughout this part. Warning Correspondence SQL was carried out starting from tests carried out with the supplier Hibernate and a data base MySQL. here a first simple example which will enable you to more easily include/understand the continuation of the explanations. The operator ". under sorrow which PersistanceException is launched.. in this example. Those must be declared via the expression HAVE. to call the method Portfolio. it should be retained that it acts of an abstract representation of Entity Bean.

to check that the constraints of modifications in cascade were indeed applied. With EJB 3. user0_. you must carry out several requests.login as login4_.birthDate as birthDate4_ from XUser user0_ where user0_. the data bases of the type MySQL version 5 and the engine of InnoDB storage.firstName as firstName4_. However. The following request recovers. Thus.lastName as lastName21_. it will be necessary all the same to manually write their withdrawal of the data base. user0_. Contraintes pour la table `FINANCIALPRODUCT` ALTER TABLE `FINANCIALPRODUCT` ADD CONSTRAINT `fk2` FOREIGN KEY (`portfolio_fk`) REFERENCES `portfolio` (`id`) ON DELETE CASCADE.password as password21_. DELETE FROM User AS user WHERE user. In this last case.lastName as lastName4_. even if the relation is configured with CascadeType. user0_. In this request DELETE.id = 1 update XUser set firstName=? where id=? Clause DELETE of EJBQL does not support the suppression in cascade. SELECT user FROM User AS user WHERE user. represent only one character.login as login21_. The preceding example works directly with the User object. First is "%" and it is used for a number of indefinite natures. To explicitly write all requests EJBQL of suppressions in the good order. it should well be understood that the difference comes owing to the fact that EJBQL is directed object.password as password4_.address_fk as address8_4_.lastName as lastName4_. SELECT user FROM User AS user WHERE user. user0_. user0_. In this way. user0_. at the time of the removal of a user. Their common characteristic is to have only one entity in clause FROM.lastName FROM User AS user select user0_. It is enough to specify them in clause SELECT.id as id21_. user0_.firstName = "Durand" WHERE user. The following example selects all the users having an identifier of 1500 to 2000..sex as sex4_. financial products. we are likely to receive exceptions if Entity Bean User would have relations.id.sex as sex4_. SELECT user.id as id4_.firstName as col_1_0_ from XUser user0_ Requests DELETE and UPDATE These requests will provide a whole of operations to modify or remove Entity Bean. user0_. Clause WHERE The permissions included in clause WHERE exist for the majority in a similar form with that which one can use in SQL. If your character string would use really these two characters.address_fk as address8_4_. user0_.id as col_0_0_. ?To use? corresponds to the abstract diagram of Entity Bean User and ?usr? corresponds to one alias (as in SQL). Here two examples showing the use of these requests. and information will be automatically removed. user0_. "_". Here a list summarizing those most usually used: BETWEEN: conditional operator allowing to restrict the results according to an interval. user0_. user0_.login as login4_.firstName as firstName4_.sex as sex21_. You will have. however it is sometimes practical to recover only the id. user0_. We have three possibilities then: To use the manager of persistence which applies the suppression in cascade.net/Booster/Pages/lectureSimpleViewer.firstName as firstName21_.birthDate as birthDate21_ from XUser user0_ There are many similarities with language SQL.firstName like ? The reason is built with two special characters. The second. user0_.id = 5 delete from XUser where id=? UPDATE User AS user SET user. user0_.address_fk as address8_21_. user0_.firstName LIKE 'jean%' select user0_. user0_.campus-booster.REMOVE or CascadeType. you https://www.birthDate as birthDate4_ from XUser user0_ where user0_. user0_. all the accounts having a first name starting with "Jean". for example. it is possible to specify the properties which one wishes to recover.aspx?lecture=814&PM=True Page 39 of 100 . user0_. Indeed. before. In the preceding example.id between ? and ? LIKE: allows to compare the value of a field with a specified reason. user0_. user0_. user.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 SELECT usr FROM User AS usr select user0_.id as id4_. all his wallets.ALL. Contraintes pour la table `Portfolio` ALTER TABLE `Portfolio` ADD CONSTRAINT `fk3` FOREIGN KEY (`user_fk`) REFERENCES `xuser` (`id`) ON DELETE CASCADE.id BETWEEN 1500 AND 2000 select user0_. user0_. Here an extract of code SQL to be used: ­­ Contraintes pour la table `AccountInfo` ALTER TABLE `AccountInfo` ADD CONSTRAINT `fk1` FOREIGN KEY (`id`) REFERENCES `xuser` (`id`) ON DELETE CASCADE. or the first name..password as password4_. To use the possibilities of the data base and to manage the suppression cascade about it on the level of this one. it?s possible to use the expression ON DELETE CASCADE for. or the name. for example. if you wish to remove or modify recordings of several different Entity Bean.

Address address1_ where user0_.util.login as login21_.firstName as firstName4_. user0_. DESC should be used (larger with smallest).. user0_.birthDate as birthDate4_ from XUser user0_ order by user0_.id as id21_. Clause ORDER BY Clause ORDER BY makes it possible to arrange by order the results of a request. user0_.. SELECT user FROM User AS user WHERE user. To know exactly the implementation of this function. user0_. user0_.id as id21_. user0_.password as password21_.firstName as firstName21_. SELECT user FROM User AS user WHERE ?1 MEMBER OF user.sex as sex21_. Results of an ORDER BY ID First name 4 6 7 8 Cyril Frederic Olivier Maxime 10 Jean-Baptiste Key word optional ASC means that the classification is made in an ascending way. user0_.password as password21_.login is null MEMBER OF: test the membership of an authority to a collection. user0_.login IS NULL select user0_.password as password4_.lastName as lastName21_. IS NOT NULL.id as id21_. user0_. user0_.birthDate as birthDate4_ from XUser user0_.net/Booster/Pages/lectureSimpleViewer. https://www. for example. 'Belgium') select user0_.address_fk as address8_4_. for example. user0_.password as password4_.Collection. user0_.lastName as lastName21_. user0_. SELECT user FROM User AS user WHERE user. just like the method contains() of the interface java. For example.address_fk as address8_21_. To carry out it in a downward way.firstName as firstName21_. and Belgium SELECT user FROM User AS user WHERE user. user0_. By defect. user0_. user0_. user0_. user0_. user0_.sex as sex21_.lastName as lastName4_. starting from one or more fields by using the alphanumeric order then alphabetical. user0_.campus-booster. such as ` java_bean'.address. user0_.sex as sex4_.password as password21_. Maxime.sex as sex4_.. Aaxime.birthDate as birthDate21_ from XUser user0_ where user0_.address_fk as address8_21_. the recordings where the login was not specified.id as id4_..address_fk as address8_4_. 'Belgique')) IS NULL: test if a value is null.portfolios select user0_.birthDate as birthDate21_ from XUser user0_ where not (exists (select portfolios1_. Martine.firstName as firstName4_.aspx?lecture=814&PM=True Page 40 of 100 . We can use it with preceding operators (NOT BETWEEN.id Here what one could recover (according to the data of the database): Table 1. It acts of the default value defined when a field was not indicated. firstname LIKE ` Ma% ' will return the entries with Marc.country in ('France' . user0_. The following request recovers. ` java _ '.id=portfolios1_. user0_. The following request returns.login as login4_. user0_.). SELECT user FROM User AS user ORDER BY user. user0_. 17/10/09 18:17 `_java' or ` _ ' IN: test a membership of a list of character strings. user0_. Spain. it is ASC which is applied..birthDate as birthDate21_ from XUser user0_ where ? in (select portfolios1_. user0_. user0_..firstName as firstName21_. Here some examples of use: firstname LIKE `_axime' will return the entries such as Maxime. user0_.user_fk)) NOT: opposite the result of the condition.login as login4_. The following example recovers the users having the wallet passed in parameter (we will further see the passage of the parameters in this chapter). NOT IN.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION have at your disposal the escape character "\".id from Portfolio portfolios1_ where user0_.lastName as lastName4_.address_fk as address8_21_.lastName as lastName21_.id as id4_.id from Portfolio portfolios1_ where user0_. user0_. user0_.id ASC select user0_.country IN ('France'. all the contacts located in France. it is necessary to refer to the handbook of the data base.login as login21_. 'Spain'. misc LIKE `%\_%' will return the entries containing the character ` _ '.id=portfolios1_. user0_.address_fk=address1_. we here will turn over the list of the users not having any wallet of action.login as login21_. The following example turns over the list of the users ordered according to their identifier. user0_. NOT LIKE. user0_.portfolios IS EMPTY select user0_. user0_.user_fk) EMPTY: test if a collection is empty.id and (address1_.sex as sex21_. 'Espagne' .

by supposing fictitious data: Table 2.lastName ASC.id as id139_. SELECT user FROM User AS user ORDER BY user.id) as col_1_0_. as follows: SELECT portfolio FROM User AS user. however when two users have the same name. user. To handle the collections with the operator IN The major part of the relations uses collections.id) as col_0_0_ from XUser user0_ It is also possible to use clause GROUP BY to apply the function of aggregation to a batch of recordings.birthDate as birthDate72_ from XUser user0_ left outer join Portfolio portfolios1_ on user0_. Thus.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION It is of course possible to combine these criteria.firstName ASC select user0_. user0_.portfolios) AS nbrPortfolio FROM User AS user GROUP BY user. First name Portfolios Cyril Frederic Maxime Olivier 2 4 1 9 Jean-Baptiste 5 The interest of GROUP BY in this request is to be able to apply function COUNT() to each user.campus-booster.net/Booster/Pages/lectureSimpleViewer. user0_. The course of their entries is particularly interesting because there does not exist in the relational logic of the SQL.lastName as lastName72_. One finds them in EJBQL via the following instructions: avg(): turn over an average by group count(): turn over the number of recordings sum(): turn over the sum of the values max(): turn over the highest value min(): turn over the lowest value sum(): turn over the sum of the values For example. you can use the function count() to know the number of users registered in your data base.lastName. We have for that the operator IN. user0_. SELECT user. as with clause WHERE.firstName HAVING nbrPortfolio > 2 Note In accordance with standards SQL.user_fk group by user0_.id as col_0_0_. the following request posts the name by ascending order.login as login72_. user0_. SELECT COUNT(user) FROM User AS user select count(user0_.id as id72_.firstName DESC 17/10/09 18:17 Functions of aggregation The functions of aggregation are used to carry out operations on sets. portfolio0_.id=portfolios1_.user_fk as user3_139_ from Portfolio portfolio0_ where portfolio0_. He must be placed in clause FROM.address_fk as address8_72_.user_fk=? https://www. portfolio0_. user0_. user0_. count(portfolios1_. user. user0_. user0_. COUNT(user. user0_. user0_.firstName ASC SELECT user FROM User AS user ORDER BY user.id as col_0_0_.lastName ASC.password as password72_.firstName. Here an example allowing to turn over the number of wallets per user: SELECT user.aspx?lecture=814&PM=True Page 41 of 100 . Clause HAVING makes it possible to specify criteria. on a column generated by one of the functions of aggregation. In the following example.portfolios) AS nbrPortfolio FROM User AS user GROUP BY user select user0_.id as col_0_0_. user0_. and makes it possible to declare alias for the entries of a collection.name as name139_. the sorting is done then on the first name.firstName as col_1_0_ from XUser user0_ order by user0_.id The results could be as follows. we can recover the whole of the wallets created.firstName DESC select user0_.firstName as col_1_0_ from XUser user0_ order by user0_. it is necessary to use clause HAVING in order to apply criteria to the result of a function. we turn over only information when the number of financial wallets is higher than 2.firstName as firstName72_.sex as sex72_. then decreasing in the second example.portfolios) portfolio select portfolio0_. user0_.lastName.firstName. COUNT(user. IN (user. For example. in an increasing way.

financialp2_.firstName as col_0_0_.productName as productN5_104_.zipCode as zipCode143_1_.accountInfo AS ai select user0_.firstName. user1_.buyValue as buyValue104_.cardNumber as col_2_0_ from XUser user0_ inner join AccountInfo accountinf1_ on user0_.cardNumber FROM User AS user JOIN user. financialp2_. user1_. AccountInfo accountinf1_ where user0_. but is in clause SELECT. For that.firstName as col_0_0_. adds the results of the second entity.numero as numero143_1_. AccountInfo accountinf1_ where user0_. financialp2_.cardNumber as col_2_0_ from XUser user0_.porfolios.sex as sex140_0_. various manners.firstName.accountId as accountId142_2_.rate as rate104_.cardNumber as col_2_0_ from XUser user0_.portfolios) FROM User AS user select portfolio0_. AccountInfo AS ai WHERE u.country as country143_1_.id as id104_.id=accountinf3_.password as password140_0_. user1_.id select user0_. IN (portfolio.address_fk as address8_140_0_. The identifiers in clause FROM are declared of left on the right. user.id as id143_1_.lastName as lastName140_0_. the expression LEFT JOIN allows systematically to include the first entity in the result of the request.id=accountinf1_. portfolio0_.id=accountinf1_.portfolios) portfolio.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION We gather the elements contained in the collection user.id left outer join Address address2_ on user1_.id By using the relational properties: SELECT user. portfolio0_.price as price104_.portfolio_fk where user0_.financialProducts) fp WHERE user. Results of a JOIN First name Cyril Ophélie Card number 1111-2222-3333-4444 2222-3333-4444-5555 The turned over results are the same ones for each request with some exceptions.id By using a joint via instruction JOIN: SELECT user.name as name139_3_. the request turns over FinancialProduct having a quantity higher than 10 of the user of id 42 (any confused wallet).city as city143_1_.cardNumber FROM User AS user. accountinf3_.firstName as col_0_0_. accountinf3_.quantity as quantity104_. https://www. SELECT ELEMENTS(user. it is necessary to carry out a joint known as "open".login as login140_0_. had by a user. financialp2_. accountinf1_.amount as amount142_2_ from Portfolio portfolio0_ left outer join XUser user1_ on portfolio0_.id Table 3.id = ai.id where portfolio0_. financialp2_.monthDuration as monthDur7_104_.firstName.id=? Joints The joints make it possible to handle the relations between the entities.quantity > 10 select financialp2_. even if they do not have a relation. in alias " the portfolio ". When a User entity does not have a relationship to the AccountInfo entity. So the request gathers the wallets of all the users and the load.buyDate as buyDate104_.campus-booster. as for it.user_fk inner join FINANCIALPRODUCT financialp2_ on portfolios1_. address2_. one uses the instructions LEFT OUTER JOIN or RIGHT OUTER JOIN.cardNumber as cardNumber142_2_. accountinf3_. the operation of the joints is subtle. financialp2_.id = 42 AND fp. address2_. accountinf1_.user_fk=user1_. SELECT fp FROM User AS user.cardNumber FROM User AS user select user0_. fulfills the same role. In EJBQL.id as id140_0_. user1_. In the preceding example.accountInfo. IN (user.id as id139_3_. the recording will not be turned over ! LEFT JOIN In order to return the recordings of the Account entity.id=financialp2_.address_fk=address2_. user1_.financialproduct_type as financia1_104_ from XUser user0_ inner join Portfolio portfolios1_ on user0_. user1_. address2_. By using the style ?théta?. financialp2_.id as id142_2_. When an identifier is declared. The following request recovers all the financial products had by the user having identifier 42. ELEMENTS. accountinf1_.id=portfolios1_. We will see that the functionalities available are multiple and will be able to adapt to many needs.portfolio_fk as portfolio10_104_.net/Booster/Pages/lectureSimpleViewer. ai. To illustrate this declaration. with the relation between primary and key keys foreign: SELECT user. user1_.aspx?lecture=814&PM=True Page 42 of 100 . financialp2_. address2_. financialp2_. Indeed.user_fk as user3_139_3_.id left outer join AccountInfo accountinf3_ on user1_. also existing in SQL. Here a request with a similar result with the first example. ai. accountinf3_. One second function.firstName as firstName140_0_.id=accountinf1_. address2_.birthDate as birthDate140_0_. RIGHT JOIN. address2_.accountInfo. user1_.id=? 17/10/09 18:17 This operator allows to directly select the elements of a relation and to work with. one can use it in the following declarations.street as street143_1_. we present the recovery of the wallets of actions.

id have id309_1 _. user0_. portfolios1_.lastName. SELECT U FROM To use U INNER JOIN FETCH u.firstName have firstName310_0 _. Thanks to this modification.getFinancialProducts().cardNumber FROM User AS user LEFT JOIN user. Here its correspondence in SQL: select user0_.financalProducts select user0_.login have login310_0 _. p.address_fk have address8_310_0 _.id have id310_0 _.lastName have lastName310_0 _. The results are then different.e. accountinf1_. It is however more familiar with the developers usually using the SQL. This request carries out a "joint open on the left".id INNER JOIN We previously saw the use of the operator IN. That poses problems of performances however.portfolios p select user0_.user_fk left outer join FINANCIALPRODUCT financialp2 _ one portfolios1_.aspx?lecture=814&PM=True Page 43 of 100 .getSingleResult().id=accountinf1_.id=financialp2_.firstName as col_0_0_.iterator(). user.cardNumber as col_2_0_ from XUser user0_ inner join AccountInfo accountinf1_ on user0_. i.portfolios) p FETCH JOIN We saw previously that it was possible to use a mechanism of the lazy loading.birthDate have birthDate310_0 _. the request from now on took into account the third recording. The following example uses an open joint. portfolios1_.id The preceding request turns over the whole of the wallets created whatever the user. when the application reaches a property marked with lazy.portfolio p LEFT JOIN FETCH p.createQuery("SELECT u FROM User u WHERE u. user0_. Here correspondence using ?IN?: SELECT p FROM User u.user_fk have user3_0 __. the requests relating to a hierarchy of objects. portfolios1_.net/Booster/Pages/lectureSimpleViewer.lastName as col_1_0_. In this case. To optimize that. } This example charges the user of id 1 and initializes its wallets and the associated financial products. user0_.next(). It is however simpler to use the operator IN. SELECT user.sex have sex310_0 _. only one request is carried out. Iterator<Portfolio> portfoliosIt = user. The joint of the type ?INNER? causes the same result.name have name309_1 _. the engine of persistence must carry out a request with line 2 then for each loading of the associated financial products (line 5). SELECT p FROM User u INNER JOIN u. Indeed. https://www. it is necessary to use a request EJBQL with a joint of the type ?FETCH?.portfolio_fk A joint ?fetch? does not need normally to define alias except when you wish to use the concept of the ?fetch recursively?. ai. user0_.id have id0 __ from XUser user0 _ left outer join Portfolio portfolios1 _ one user0_. while(portfoliosIt.user_fk have user3_309_1 _. 1).firstName.accountInfo AS ai Table 4. IN(u. it is strongly advised to avoid too much outward journey and return with the data base. It is enough to use key word INNER JOIN to carry out this type of joint. used in SQL.hasNext()) { Portfolio p = portfoliosIt.id=portfolios1_.campus-booster. User user = (User) query.cardNumber as col_2_0_ from User user0_ left outer join AccountInfo accountinf1_ on user0_. portfolios1_. user0_. became optional. user0_. accountinf1_. the supplier of persistence must charge it.password have password310_0 _.firstName as col_0_0_. Indeed. The use of this type of joint in a program is a need for the optimization and the improvement of the performances. user0_.accountinfo_fk=accountinf1_. Query query = entityManager. user0_.lastName as col_1_0_.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 Note Instruction OUTER. Results of a LEFT JOIN First name Cyril Maxime Card number 1111-2222-3333-4444 2222-3333-4444-5555 Jean-Baptiste NULL Indeed. which does not have a relation with AccountInfo.getPortfolios().size().id = :userId"). Management of Polymorphism EJBQL supports polymorphism. portfolios1_. user0_.setParameter("userId". This one operates N+1 requests then (N being the number of wallet).

the use of joints or instructions such as IN. initially. user0_.getResultList(). One of the principal interests of the underrequests is to be able to replace the joints. i.id as id327_.password as password327_.id) from Portfolio portfolio1_ where portfolio1_. The corresponding methods are gathered in the EntityManager interface. user0_.net/Booster/Pages/lectureSimpleViewer.Query. SELECT user FROM User user WHERE ( SELECT COUNT(portfolio) FROM Portfolio AS portfolio WHERE portfolio. The methods of this one are gathered in the interface javax. user0_. user0_.login as login327_. When under request is likely to turn over several lines.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 The execution of the following request turns over all the recordings dependent on the FinancialProduct entity and thus of its subclasses. https://www. user0_. Like their equivalent SQL. SOME turns over true so at least a result checks the condition ANY turns over true if no result checks the condition API Query API Query is the essential point for the junction between the application and the execution of requests EJBQL.portfolio IN ( SELECT portfolio FROM Portfolio AS portfolio WHERE portfolio.birthDate as birthDate327_ from XUser user0_ where (select count(portfolio1_. SELECT fi FROM FinancialProduct AS fi The collection of result contains objects of the Bond type or Stock.address_fk as address8_327_. one uses the expressions: ALL turns over true if all the results of the request checks the condition. We recover a Query object here via the method createQuery() of EntityManager..login = 5 ) ) delete from FINANCIALPRODUCT where portfolio_fk in (select id from Portfolio portfolio1_ where portfolio1_. We advise you to study.. user0_.id group by user0_.persistence. in particular in the requests of the type UPDATE and DELETE. the concrete types of the hierarchy.sex as sex327_. Under requests The underrequests can beings placed in clauses WHERE and HAVING.user_fk=user0_. The principal interest of this API is to be able to create dynamic requests in the form of simple character strings. user0_. Here a simple example: Query query = entityManager.user IN ( SELECT user FROM User AS user WHERE user. which are obligatory besides in systems not taking into account the underrequests.user=user GROUP BY user ) >3 select user0_.firstName as firstName327_. List<User> listUsers = query.e. ELEMENTS. It is then enough to call the method getResultList() to carry out the request and to recover the result of this one. The following request removes all the financial products where the user has a id having for value 5: DELETE FROM FinancialProduct AS fp WHERE fp. The following example selects the users having more than 3 financial wallets. it is then possible to quantify the result having to be turned over.campus-booster.id)>? It is noticed that one alias reuses to use of the principal request in the underrequest.id = 5)) Note Use the underrequests when you cannot make differently.user_fk in (select id from XUser user2_ where user2_. We will progressively detail the various methods of this one. and either a static way in the descriptor of deployment.createQuery("SELECT user FROM User As user"). There are various means of recovering an object of the Query type. For that. they make it possible to imbricate the requests.aspx?lecture=814&PM=True Page 44 of 100 .lastName as lastName327_.

8.campus-booster. If the number of results is higher than 1.createQuery("SELECT user FROM User AS user WHERE user. Practices Questions 1. Furthermore. The trade layers are also more efficient and simpler to write.9. Conclusion In this essential about EJB3.2. the method getResultList() turns over a list of table of object (" Object[ ] ").6. if the request tries to turn over several thousands of lines. Choose the best example representing a "Many to many" relationship: A dog has an owner.1. This method carries out the request and turns over a single result. a student has many teachersA mailbox belongs to an house. It is then possible to specify several properties in clause SELECT in order to recover only certain values of the entity. Query query = entityManager. So we are sure that the method cannot return several results. during the setting up of this technology. query. Query query = entityManager. What are the different JMS distribution models? Peer to peerPoint to pointPublish and subscribeSend to all 1.setMaxResults(30). an owner has many dogsA teacher has many students. } In this case.lang.login = 'durand. List<Object[]> listUsers = query. String name = (String) valueArray[1]. What does EJB means : Enterprise Java BeansEnterprise Java BasesEntity Java BeansEntity Java Bases 1.getSingleResult().7. Which of these beans are valid Session beans: Remote session beanLocal session beanCommon session beanUnique session bean 1.5.getResultList(). if no result is found. an owner has many dogsA teacher has many students.createQuery("SELECT user. What is the difference between Stateful and Stateless session beans? It's the same thingThey're not relatedA stateless session bean keep information between two calls while stateful forget thoses informationsA stateful session bean keep information between two calls while stateless forget thoses informations 1. In this example. a house has a mailbox 1. List<User> listUsers = query. for(Object[] valueArray : listUsers){ Integer id = (Integer) valueArray[0].List getResultList(). The @Id annotation is used to specify a primary key. Choose the best example representing a "One to one" relationship: A dog has an owner. It makes it possible for example to recover a whole of Entity Beans complete.lastName FROM User As user"). Wich of thoses servers can handle EJB? GlassFishJBossTomcatOracle Application Server 1. we've first seen that they locate in the center of your application. Choose the best example representing a "One to many" relationship: A dog has an owner. a house has a mailbox 1.net/Booster/Pages/lectureSimpleViewer. User currentUser = (User) query. the code writing is kind of simple and is very well inscribed in the Java object Model. the complicated thing being to understand and to analyse the application architecture. a student has many teachersA mailbox belongs to an house. Moreover.Object getSingleResult(). java.getResultList(). providing lots of assets (like the object persistence's one and a functionnal and performant client/server model). you are likely to quickly reduce the performances of your application.1.dupont'").setFirstResults(10).10. java. Conversely. an owner has many dogsA teacher has many students. a student has many teachersA mailbox belongs to an house. How do you get an entity away from the database: Using the remove() method Using the delete() method Using the clear() method Using the erase() method 1. user.. 17/10/09 18:17 This method carries out the request and turns over the whole of the results of this one. query. setMaxResults(int max) and setFirstResult(int first) These two methods respectively define the maximum number of results and the index of the first element to be turned over. one generally does not work with the whole of the results of only one blow but left by part.createQuery("SELECT user FROM User As user").id.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Here a description of the various traditional methods of the Query interface. a house has a mailbox 1. an exception of the EntityNotFoundException type is raised.util.. Those make it possible to limit the results of the request. in the form of table. Query query = entityManager. What does EJB means : Enterprise Java Beans Enterprise Java Bases Entity Java Beans Entity Java Bases https://www. How does it works? It specify the column choosen to sort multirow requestsAn attribute used as an identifier of the objectIt's like a foreign key but in local onlyIt's a table identifier common to all instances of the class 1. This method must be used only if you are sure that the request turns over only one single result. a NonUniqueResultException exception is raised. Indeed. the property login is single.aspx?lecture=814&PM=True Page 45 of 100 .3.4.

7. What are the different JMS distribution models? Peer to peerPoint to pointPublish and subscribeSend to all https://www.3.2. Which of these beans are valid Session beans: Remote session bean Local session bean Common session bean Unique session bean 1. What are the different JMS distribution models? Peer to peer Point to point Publish and subscribe Send to all 1. an owner has many dogs A teacher has many students. What is the difference between Stateful and Stateless session beans? It's the same thing They're not related A stateless session bean keep information between two calls while stateful forget thoses informations A stateful session bean keep information between two calls while stateless forget thoses informations 1.3.8. a student has many teachers A mailbox belongs to an house. an owner has many dogs A teacher has many students.campus-booster. How does it works? It specify the column choosen to sort multirow requests An attribute used as an identifier of the object It's like a foreign key but in local only It's a table identifier common to all instances of the class 1. an owner has many dogs A teacher has many students.10. Choose the best example representing a "One to many" relationship: A dog has an owner. a house has a mailbox 1.aspx?lecture=814&PM=True Page 46 of 100 .SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 1.1. What does EJB means : Enterprise Java BeansEnterprise Java BasesEntity Java BeansEntity Java Bases 1.2. The @Id annotation is used to specify a primary key.4. a student has many teachers A mailbox belongs to an house. Choose the best example representing a "Many to many" relationship: A dog has an owner.9. Choose the best example representing a "One to one" relationship: A dog has an owner. a house has a mailbox 17/10/09 18:17 Answers 1.net/Booster/Pages/lectureSimpleViewer. Which of these beans are valid Session beans: Remote session beanLocal session beanCommon session beanUnique session bean 1. How do you get an entity away from the database: Using the remove() method Using the delete() method Using the clear() method Using the erase() method 1.5. Wich of thoses servers can handle EJB? GlassFish JBoss Tomcat Oracle Application Server 1. a student has many teachers A mailbox belongs to an house. a house has a mailbox 1.6.

a house has a mailbox 1. a house has a mailbox 1. a student has many teachersA mailbox belongs to an house. How does it works? The annotation specify the column choosen to sort multirow requests An attribute is used as identifier of the object It's like a foreign key but in local only It's a table identifier common to all instances of the class https://www.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 1. Choose the best example representing a "Many to many" relationship: A dog has an owner.Many to one" relationship: A dog has an owner.4. What does EJB means : Enterprise Java Beans Enterprise Java Bases Entity Java Beans Entity Java Bases 17/10/09 18:17 1. a house has a mailbox 1. How do you get an entity away from the database: Using the remove() method Using the delete() method Using the clear() method Using the erase() method 1. a student has many teachersA mailbox belongs to an house.7.6.5.aspx?lecture=814&PM=True Page 47 of 100 . The @Id annotation is used to specify a primary key. The @Id annotation is used to specify a primary key.10.8.9. Choose the best example representing a "One to many . an owner has many dogsA teacher has many students. How does it works? The annotation specify the column choosen to sort multirow requestsAn attribute is used as identifier of the objectIt's like a foreign key but in local onlyIt's a table identifier common to all instances of the class 1.campus-booster. an owner has many dogsA teacher has many students.3. What is the difference between Stateful and Stateless session beans? It's the same thingThey're not relatedA stateless session bean keep information between two calls while stateful forget thoses informationsA stateful session bean keep information between two calls while stateless forget thoses informations 1.5. a student has many teachersA mailbox belongs to an house. Which of these beans are valid Session beans: Remote session bean Local session bean Common session bean Unique session bean 1.net/Booster/Pages/lectureSimpleViewer.2. What is the difference between Stateful and Stateless session beans? It's the same thing They're not related A stateless session bean keep information between two calls while stateful forget thoses informations A stateful session bean keep information between two calls while stateless forget thoses informations 1. Choose the best example representing a "One to one" relationship: A dog has an owner. What are the different JMS distribution models? Peer to peer Point to point Publish and subscribe Send to all 1.1. an owner has many dogsA teacher has many students. Wich of thoses servers can handle EJB? GlassFishJBossTomcatOracle Application Server 1.4.

SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 1.campus-booster.10.net/Booster/Pages/lectureSimpleViewer. a student has many teachers A mailbox belongs to an house.7. a house has a mailbox Chapitre 2 JSF Web framework Objectives of this chapter : Know when to use JSF Understand its architecture Display web pages Validate forms Realize that a web application can be very close from a Swing application. Choose the best example representing a "One to one" relationship: A dog has an owner.9. a house has a mailbox 1. a student has many teachers A mailbox belongs to an house. Choose the best example representing a "One to many .6. Wich of thoses servers can handle EJB? GlassFish JBoss Tomcat Oracle Application Server 17/10/09 18:17 1.Many to one" relationship: A dog has an owner. Choose the best example representing a "Many to many" relationship: A dog has an owner. How do you get an entity away from the database: Using the remove() method Using the delete() method Using the clear() method Using the erase() method 1. a student has many teachers A mailbox belongs to an house. an owner has many dogs A teacher has many students. an owner has many dogs A teacher has many students.aspx?lecture=814&PM=True Page 48 of 100 . an owner has many dogs A teacher has many students. a house has a mailbox 1.8. https://www.

Sun provides a reference implementation for each version. numerous JSF components are available on the Internet.net/Booster/Pages/lectureSimpleViewer.aspx?lecture=814&PM=True Page 49 of 100 . request or application automatically Extensibility. but only a document which describes how JSF works. Web components can holds listeners (clic on a button. From application developer.org/en/jsr/detail?id=127 for JSF 1. everyone can use JSF.2 has become a standard.jcp. Offical JSF specifications can be downloaded at : http://jcp.) Validate users requests (test field length. This transformation is done thanks to the HTML/Object mapping. Of course you can mix the two techniques. JSF offers the following services: Provides a HTML/Object mapping Save the state of JSF components between requests Transform JSF components into HTML Manage events (click on a button. define navigation file. JSF uses a HTML/Object mapping. content type. Java Server Faces presentation Java Server Faces (JSF) is a Web Framework. For example Sun has created Java Studio Creator. It?s only since JEE 5 that JSF 1. Application architect which will create application. This mapping allows us to create a site in Java or to use HTML/JSFP/JSF tags. When a user visits a page. Finally JSF manage all navigations rules into a unique file named "navigation file"..campus-booster. There are no guides to help you. JSF components will be transformed into HTML and viceversa. navigation management. an IDE dedicated to JSF and which JSF as its core. ?) on server side Instanciate and attach JavaBeans to the session. to create custom components IDE creators who will use JSF as the base of the IDE and extends JSF functionalities thanks to custom components.0 and 1. Apache provides its own one named "MyFaces" (currently only for JSF 1. Even if it?s possible to create a Site with only these technologies it?s clear that Servlet better suit for treatment and JSP for visual.. JSF version 1. ?) Manage errors and exceptions and provides clear error messages Manage navigation depending on interaction on a data model Manage internationalization JSF Audience A large audience can use JSF. JSF is based on the model MVC (ModelViewControler) and provides a notion of Web components similar to Swing.0 et http://jcp. JSF Evolution JSF is a specification proposed by the JCP (Java Community Process : www. But Servlet/JSP has some limitations: Create its own tags is difficult There are no highlevel tags It?s hard to process user inputs It?s hard for a beginner to create a Site with a clean architecture. clic on a link. It also helps to manage all commons tasks like data validation.2. So there is not only one implementation of JSF.1 were not part of J2EE.1). it means that a HTML component will be mapped to a JSF component.org ). There are three main categories of people between five. This mapping is done on the server side. ?) on server side.org/en/jsr/detail?id=252 for JSF 1. field modification. to designer.. a String into a business object and viceversa.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 Introduction Servlet / JSP limitations The first step to create a Web Site in Java is to use Servlet and JSP. https://www. It provides highlevel components to quickly create complex Web Site. This goes from calendar to tree by going through sortable table and progress bar Support a plugin system which can be used to modify the way JSF works Manage data conversion (can convert a String into a Date. This helps to see how navigation works for a Site at a glance. classes/libs to use to make the link between view and services layers Developers who implements all the Web Site Page designers who will works with HTML/JSP/JSF tags Last two categories of people which use JSF are: People who want to extends JSF.

Elements specific to JSF 1. it means that their lifecycle are managed by the container Form validation Navigation defined in only one file JSF also support events and independence of HTML rendering..1 JSTL 1. This lesson has been created for JSF 1.aspx?lecture=814&PM=True Page 50 of 100 .1 and 1.2 is based on the following librairies: JSF version 2. By default JSF use HTML/JSP/JSF tags but in the chapter "9 Facelets" we?ll see that we can use another tag libs. Check the documentation of your server before deploying a JSF application. And JSF use a file which summarize: all navigation rules https://www.net/Booster/Pages/lectureSimpleViewer.campus-booster. All components exist as Java classes.0 JEE 5.. JSF pages can be used to generate XML. ?) will maintain it.1 Servlet 2. Controller is the Faces Servlet. But they also have a different way of working. JavaBeans represents the model and are used to interact with lower layers of your application Rendering system used to translate JSP/JSF tags to HTML Obersvator/Observer system Conversion model Validation model All these services are manipulated through JSF tags.2.1 server. Then the page can use JavaBeans to define what process to execute. They provide: Managed Beans. In practice components are mostly invisible. However there may be unexpected behaviors depending on your application server. it?s like a JavaBean is directly linked to JSF tags. which is easier than in Java code. SVG.0. Each user request to Struts pages must go through a mini Servlet (action class) that can do some process and define the JSP target page.2 are specified.2 with a Servlet/JSP 2. you have to include all JSF librairies into your wars.2. But in practice all components are manipulated through JSF tags. JSF components provides: JavaBeans interaction.2 All JEE 5 application servers supports JSF 1.1 with a Servlet/JSP 2. to run JSF 1. JSF components are the view. With JSF a request is directly targeted to a JSP/JSF page. validate user input and data conversion. JSF use components to represent structure of a page. In MVC model. In a global manner. If you don?t have a JEE 5 server.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION JSF 1.3/1.5 JSE 5. Components provide methods to manage listeners. This model promotes code reuse thanks to components.2 with a non JEE 5 server. so you can use them inside Java code. you can still use JSF 1. Finally JSF is a JEE 5 standard which ensure that community and majors actors (Oracle with ADF/MyFaces. 17/10/09 18:17 Difference with Struts Struts and JSF can look the same. Struts use an actionresponse model. Sun with Java Studio Creator 2. JavaBeans represents model.0 JavaBeans 1. JSF architecture JSF is like Swing but for Web.5/2.2 server or JSF 1. There has been created to go beyond the limits of Servlet/JSP. .

a new instance of FacesContext is created and process the request. You can even do conditional navigation. JavaBeans provide access to Service layer.aspx?lecture=814&PM=True Page 51 of 100 . When a request arrive on the server. The container instantiate beans when a page need it. Class which manages lifecycle is "javax. JSF correspond to Application and Client layers. With the navigation file you can see how user request are processed. 17/10/09 18:17 JSF integration inside a JEE architecture To reuse the architecture schema from the JEE lesson. it?s also possible to directly interact with a database from JavaBeans. Here?s an example of a site architecture: LifeCycle We?ll now see how server process a JSF request. It?s possible to interact with EJBs or any other type of service layer. https://www.net/Booster/Pages/lectureSimpleViewer. JSF Servlet can be executed in a Servlet or Portlet container. And it also produces HTML from JSF tags.faces. The Servlet first retrieve the component tree which maps to a requested JSF page by looking to identifiant put inside of the HTML code. this phase is over. Then JSF Servlet create component tree which maps to the JSF page.context. Here?s an example of an application with EJB + JSF: In a small application.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION declaration of managed beans.campus-booster. This Servlet is used to transform JSF tags into components that are manipulated on the server side. Once all JSF components are instantiated.FacesContext". It transmit it to the JSF Servlet. When a client send a HTTP request to a server. JSF is made of a single Servlet. Let?s see in details how request processing works: Restore View When a request arrive on the server. JavaBeans that are declared in the configuration file are named "managed bean".

jar ". allow usage of standard tags.campus-booster.2. to create logs For JSF 1. Event processing will be review in details in the chapter: " Behaviors ". These jars must be placed under "WEB-INF/ lib" of Web archive (War).1 or JSF 1. <?xml version='1. the simplest thing is to use a JEE 5 server. Some components can trigger an event once its value change. You can download GlassFish at: https://glassfish. This include events triggered during "Apply Request Values" phase. You can download Sun implementation at: http://java. contains JSF classes definition (package javax. Develop with JSF What are the steps to develop a JSF application? We?ll now see with a "Hello World" what are the minimal steps to create a JSF site. JSF page is translated to HTML. Install JSF Activate JSF in "web.faces) " jsfimpl.sun. Invoke Application During this phase.faces.dtd"> <web-app> <display-name>Application name</display-name> <!--Faces Servlet --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax. jar ". Process Validations Components that accept user entry can define validation rules. Render Response In this last phase.2 on a server that don?t support JSF. values of textfields are set to components which reprensent these text fields.dev. contains implementation of JSF classes " jstl. you have to download an implementation. Jars necessaries to JSF 1. These tags are referenced by JSF implementation " commonsbeanutils. utility classes to manipulate JavaBeans " commonsdigester . Update Model Values From now. In this example.html In the "lib" folder of the zip file. contains JSF classes definition (package javax. Servlet process these rules during this phase. jar ". These tags are referenced by JSF implementation " standard. this means that destination page is determined. allow usage of JSTL tags. all update values has been done on components. there are all jars necessaries to develop a JSF application.com/dtd/web-app_2_3. Servlet set all news values to corresponding component. To use JSF 1.aspx?lecture=814&PM=True Page 52 of 100 .jar ". The property "immediate" can be used to force processing of validation rules during the phase "Apply Request Values". Finally the navigation is resolved. jar ". contains implementation of JSF classes Enable JSF First activate JSF in "web.net/ .sun. JSF support is integrated. we?ll redirect all requests which begins with "/faces/" to JSF Servlet. to manipulate XML " commonscollections.FacesServlet</servlet-class> https://www. In this case.faces) " jsfimpl. These events are processed during the "Invoke Application" phase or immediately if the "immediate" attribute is set to true.com/javaee/javaserverfaces/download. Inc.2.webapp.1 are: " jsfapi. jar ".xml" file Create JSF pages Create JavaBeans (optional) Configure application with "faces-config.3//EN" "http://java.0' encoding='UTF8'?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems.jar ". jar ". The model (JavaBeans) which are mapped to components will now be updated to reflect these new values. all events are processed.java.xml".net/Booster/Pages/lectureSimpleViewer.//DTD Web Application 2. jar ". extension to Collections framework " commonslogging. jar ".SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Apply Request Values 17/10/09 18:17 If parameters has been passed with the request. necessaries jars are: " jsfapi. You have to create a redirect user requests to JSF Servlet.xml" file (optional) JSF installation If you want to use JSF 1. For example if an user send an form.

xml *. A War must have the following structure: Table 1.jsp" is used to access JSF pages.sun. All pages need to have the ".jsp" extension when you create it. Here?s another example of mapping.. WEB-INF/faces-config.jsf".w3.campus-booster. To acess a page you have to type it?s URL but replace its extension with ".com/xml/ns/javaee" xmlns:xsi="http://www.com/xml/ns/javaee http://java. It?s the root tag for all others JSF tags.com/xml/ns/javaee/webapp_2_5.net/Booster/Pages/lectureSimpleViewer. An url like "/faces/index. WEB-INF/classes WEB-INF/lib WEB-INF/web. we can see we can display text directly on the page. the request will not go through JSF Servlet and all JSF tags will not be processed.faces. Hello World Now that JSF is activated we can write our first. see chapter "6.sun. Here?s a basic page: <%@ taglib uri="http://java. we have: https://www. It?s a JSF parameter that you can modify.FacesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsp" extension.aspx?lecture=814&PM=True Page 53 of 100 . JSF Servlet look for "index.jsf" page.1. The only difference is the <f:view>. The following is a classic HTML structure. <web-app> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.jsp All jsp pages Contains java classes (like JavaBeans) All libraries (jars) of the project.</f:view> tag.sun. header of the file is: <?xml version='1.xml Configuratin file(optional) For example in JSF 1. When client ask for "index.jsp" on the server and process it like a JSF page. especially for internationalization.xsd"> JSF pages must have ".com/jsf/html" prefix="h" %> <html> <head> <title>First JSF page</title> </head> <body> <f:view> Hello World </f:view> </body> </html> The first 2 lines declare JSF taglibs.jsp).2.sun. However it exists dedicated tags for output.3 Context parameters".sun..webapp.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java. If you try to access directly the jsp page (/index.jsf" extension.5" xmlns="http://java. there must be packaged into a War (Web Archive).jsf</url-pattern> </servlet-mapping> </web-app> Although you access page by using a ". In this example.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.0' encoding='UTF8'?> <web-app version="2. War Structure Once the JSF pages are created.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 </servlet> <!--Mapping--> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> </web-app> For JSF 1.

3.Display errors message about the field 'lastName' --> <h:message for="lastName" style="color: red"/> <br/> <!--Text field for the first name --> <h:inputText id="firstName" required="true" size="21" maxlength="20" value="#{user. There are only 2 pages.jsp": <%@ taglib uri="http://java. too short password. When the user submit it. you have to delete the MyFaces jars on JBoss. https://www. Now we?ll look at the bean class: package com.0.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 Deployment Even if your server supports JSF.sar/jsf-lib If "default" is the configuration that you use. you can put them in the folder "TOMCAT_HOME/shared/ lib". Let?s start with the form page.net/Booster/Pages/lectureSimpleViewer.firstName}"> <h:outputLabel for="firstName" value="First name: "/> <f:validateLength minimum="3" maximum="20"/> </h:inputText> <h:message for="firstName" style="color: red"/> <br/> <!-. If they?re validation errors (missing field. If you want to use the Sun implementation. This support is based on the implementation of Apache : MyFaces.Text field for the password --> <h:inputSecret id="password" required="true" size="21" maxlength="20" value="#{user.1 since its version 4.sun.com/jsf/html" prefix="h" %> <html> <head> <title>Register</title> </head> <body> <f:view> <h1>Register</h1> <h:form> <!--Text field for the last name--> <h:inputText id="lastName" required="true" size="21" maxlength="20" value="#{user.labosun.lastName}"> <!--Label of this text field --> <h:outputLabel for="lastName" value="Last name: "/> <!-.aspx?lecture=814&PM=True Page 54 of 100 . data of the form are displayed in a second page. ?) messages are displayed directly on the form. you can copy all the JSF jars in the libraries folder of the server. you can package your own JSF jar because it?s always the jar of the server which have priority.Validator: the name length must be betwenn 3 and 20 --> <f:validateLength minimum="3" maximum="20"/> </h:inputText> <!-. Support of JSF 1.sun. so you have to check the server documentation to find the good folder. The web site uses validation and errors displaying. The goal is to show how look JSF tags and code. This folder is specific to the server. For example in Tomcat.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java. Example We?ll now see a little web site made in JSF. They are on the folder: JBOSS_HOME/server/default/deploy/jboss-web-tomcat55.campus-booster. Then.lastName}" allows to use a JavaBean. you have to package the Sun jars of JSF 1. Here "user" is the name of a bean and "lastName" is the name of one of its properties. private String firstName. public class User { private String lastName. The first display a form used to register. If you want to add support of JSF on a server. "Register.2 is planned for JBoss 5.password}"> <h:outputLabel for="password" value="Password: "/> <f:validateLength minimum="3" maximum="20"/> </h:inputSecret> <h:message for="password" style="color: red"/> <br/> <h:commandButton value="Submit" action="success"/> </h:form> </f:view> </body> </html> Syntax "#{user.1 into your War. site navigation mechanisms. JBoss JBoss supports JSF 1.

} public String getFirstName() { return firstName. the following messages are displayed: https://www.campus-booster. <managed-bean> <!-. This page display the lastname and the firstname of the user.jsp</from-view-id> <navigation-case> <!-. he goes to the confirmation page.net/Booster/Pages/lectureSimpleViewer.lastName}" /> </f:view> </body> </html> As you can see. } public void setPassword(String password) { this. } } Now let?s see the configuration file of JSF (faces-config.firstName} #{user. password = password. This file gives a name to the previous bean.aspx?lecture=814&PM=True Page 55 of 100 .xml). the confirmation page is displayed: If the form is not valid..firstName = firstName. the code for the submit button is: <h:commandButton value="Submit" action="success"/> "Action" attribute define a string which will be linked to the confirmation page. } public void setFirstName(String firstName) { this.Bean scope --> <managed-bean-scope>session</managed-bean-scope> </managed-bean> Finally we?ll look at the Confirmation page. } public void setLastName(String lastName) { this. The last step for this demo is to define a navigation rule. so when the user click and the submit button.User</managed-bean-class> <!-.jsp</to-view-id> </navigation-case> </navigation-rule> Now we?ll see the result: Site design is not good. When the user submit the form. lastName = lastName.prenom}" is used again here to reference the bean.com/jsf/html" prefix="h" %> <html> <head> <title>Registration</title> </head> <body> <f:view> <h1>Successful registration </h1> Welcome <h:outputText value="#{user.sun.Bean Class --> <managed-bean-class>com. For recall.sun.String used by the start page --> <from-outcome>success</from-outcome> <!--Destination page--> <to-view-id>/Confirmation. Confirmation. but we?ll see later how to do it better.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 private String password.labosun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java. public String getLastName() { return lastName. } public String getPassword() { return password.Name of the bean inside JSF page --> <managed-bean-name>user</managed-bean-name> <!-.jsp : <%@ taglib uri="http://java. syntax "#{user. <navigation-rule> <!--Start page --> <from-view-id>/Register.

UIComponent implements this interface.component. Interface StateHolder NamingContainer ValueHolder EditableValueHolder ActionSource Description For component that maintain a state between user requests. combo box. public int getId() {. This class definie attributes shared by all JSF components.faces. it must be unique. The value can be converted in a specific type. public class UIComponent { private int id.1 Customize messages".. For example.3 Data conversion".component". And you can defini validation rules for editing. Used to display messages. So they are 2 categories of components. Example : a HTML link fire an event. The following table sum up all generic components. Represents a form.. This components are not specifics to HTML. They?re all from the package "javax. form. but if you define one. define the method of a bean that will validate the used entry.. That?s why there is generic rendering system for tags and different implementations for every language. This property is accessible directly from a JSF tag with an attribute of the same name. They are in the package "javax.html". Used to manipulates data from a Collection ..} public void setId() {. Used to display text. define the method that will be called when the value of the component change.2 Messages management". https://www. Group JSF components into a single one. see chapter "7. you can write: <h:baliseJSF id="identifiant " /> Be careful: JSF tags can?t use some properties. So all JSF implements it.UIComponent". you?ll use JSF tags to use components and the attributes of the tag to call the properties or methods of this component.faces. The value of the component can be edited and when it happens. Table 2. See chapter "8.component. an array or a ResulSet. Generics behaviors JSF is independent from HTML. HTML specific components subclass a standard component. interface " ActionSource " has been subclassed into " ActionSource2 ". Extend ValueHolder. a event is fired on the server side. Indicates that all children components must have a unique Id. It define the method that will be called when the user activate this component. Behaviors There are 5 interfaces that can define a behavior to components. Note: In JSF 1. but provide similar functionalities: links.2. . list. The component has a value.. buttons.} } And for any JSF tag. JSF components which implements ActionSource has the attribute "actionListener ". In practice. the first for generic JSF and the second one for HTML.net/Booster/Pages/lectureSimpleViewer. "valueChangeListener".SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION You can customize these messages as explained in the chapter "8.campus-booster. This value can be linked to a JavaBean. For example. Used to enter data. Class (implemented interfaces) UICommand (ActionSource) UIData (NamingContainer) UIForm (NamingContainer) UIGraphic UIInput (extends UIOutput) (EditableValueHolder) UIMessage et UIMessages UIOutput (ValueHolder) UIPanel UISelectBoolean (extends UIInput) Description Root class for all components that can fire an event. JSF components which implements EditableValueHolder has the following attributes: "validator". JSF tags which implements ValueHolder has a "converter" attribute. you can convert the String "10/05/06" into a Date object directly. It?s used to define how the value must be converted to another type. State that this component will fire an event when the user activates it. when a user click on it..aspx?lecture=814&PM=True Page 56 of 100 . It?s not mandatory to set an Id (server will automatically define one). table.2. 17/10/09 18:17 Basic elements Root class of all components in JSF is "javax. the UIComponent class define a property "id". Behaviors are detailed in chapter "Behaviors". There are some tags attributes that don?t map to component property or method. Table 1.faces. Used to display pictures. But in practice there is only the HTML implementatio.

You can used any variable of a page just by using its name. also share the same javascript attributes.isDigit()). onchange.This syntax use an object oriented notation. They are to way to bind a component to a JavaBean: Only the value of the component is bind to a JavaBean property (only for component that has a value). This lesson only cover JSF aspects of this syntax. ondblclick. this attribute affect the lifecycle.2 it?s been unified with JSP language under the name Unified Expression Language. '>' and '&' are converted into HTML code. it?s recommended to use short id. Here?s a list of javascript attributes: " onclick.method} https://www. Example: #{javaBean.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION UISelectBoolean (extends UIInput) (EditableValueHolder) UISelectMany (extends UIInput) (EditableValueHolder) Used to manipulate a Boolean value. All these components have the following attributes.campus-booster. A indentifier must respect the following rules: It must begins with a letter (see method String. et onsubmit ". onmouseout. onmousedown. It?s not mandatory to use an id. Example: <h:baliseJSF styleClass="title1" /> escape Only some components have this attribute. If set to true. Linking between JSF Components and JavaBeans JavaBeans represents the model part into the MVC model. onblur. onreset. onkeyup. onkeypress. From this variable you can use any property or method. You can use previous attributes and the following attributes: CSS style This attribute define the CSS code of the tag. Here?s an example with the tag <h:outputText /> that display a text. It web specific language. Used to select multiples values from a list. onclick. An EL expression start with "#{" and end with "}". JavaScript events All tags that represents a HTML tags. The syntax to use JavaBean in JSF tags is EL (Expression Language). HTML components HTML components are located in the package "javax. Others characters can be letters. onfocus. onmouseover. color: red" value="Hello"/> That?s translated in the following HTML : <span style="font-size: 150%. The component itself is bind to a JavaBean property.html". <h:outputText style="font-size: 150%. onkeydown. characters '<'. digits (see method Character. Example: <h:JSFtag id="identifier" /> Note: To optimize JSF performance. onmouseup. onselect. ondblclick.isLetter()) or the character '_'. 17/10/09 18:17 UISelectOne (extends UIInput) (EditableValueHolder) Used to select a single value from a list.5 Unified Expression language" details all JSF features of this syntax. color: red">Hello</span> CSS class It defines the CSS class of a tag.component. Attribute id This attribute defines an identifier for component.'' or '_'.aspx?lecture=814&PM=True Page 57 of 100 . See chapter "5 JSF Taglib" for a complete list This chapter only covers commons attributes of these components.Character.faces. Renderer attribute It?s a boolean that define if the components is displayed or not Example: <h:JSFtag renderer="false" /> This attribute can be used to display a message only if a search has returned no results. Since JSF 1.net/Booster/Pages/lectureSimpleViewer. The next chapter "4. This model clearly separate different layer of an application. It?s useful to reference components on a page. Immediate attribute As seen in chapter " LifeCycle". onmousemove.

the session or the application. For example a text field accept a "String". For example to access "name" property of "person". you?ll write: https://www. } } And then.0 under the name Expression Language. Collection. JavaBean array or list. public HtmlOutputText getComposant() { return this.2 that the language has been unified under the name "Unified Expression Language". UISelectItem. javax. For example.property}" /> There are restrictions on the type that you can bind: Table 3.Result or javax. } public void setComposant(HtmlOutputText c) { this. Component UIInput.jsp. Instance If you want to bind a component instance to a bean property. "." Operator is used to access a property. Unified Expression language Unified EL (Unified Expression Language) is language created to propose a simple way to access Java code from tags. Simple JavaBean. a "Number" or a primitive as value. This syntax has appeared with JSP 2. if you want to bind the component HtmlOutputText to a JavaBean.composant = c.servlet.0 and JSF 1. By default Servlet version 2. remember that it?s generally bad to mix JSF and JSP EL expressions (like mixing AWT and Swing). a String. Tableau or Map Array or List. See chapter "7.campus-booster.jstl.3 and previous ignore this syntax. A text field is represented by the class "HtmlInputText".sql. So attribute "value" must have the same type. The class hierarchy is: Attribute "binding" can be any of these types. you just specify the bean property with the attribute "binding": <h:outputText binding="#{linkedBean. you have to use the attribute "value" and specify the referenced bean with EL syntax.property} Value To bind the value of a component to a bean property.1 and JSF 1.ResultSet. method of an bean. In JSF we use "#{}". Without explain differences between these 2 syntaxes.sql. The best way is to use only JSF syntax and replace JSP tags by their equivalents in Facelets tags (see chapter "9 Facelets"). For example: #{person} The Web (or Portlet) container will look for an object which is named "person" in the page.composant. Restrictions will be detailed in following chapters. UIOutput. boolean or Boolean String.net/Booster/Pages/lectureSimpleViewer. a Number or any class that have a converter. Example: <h:JSFTag value="#{javaBean. java.sql.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 #{javaBean.aspx?lecture=814&PM=True Page 58 of 100 . the request.composant}" /> Difference between attributes "value" and "binding" is that "value" only bind the value of component and "binding" bind the component instance. UISelectOne UIData UISelectBoolean UISelectItems UISelectMany Possible values A primitive. Variables It?s possible to reference any object in a page. You first declare the following property: public class LinkedBean { private HtmlOutputText composant. It?s possible to change this behavior with the directive: <%@ page isELIgnored ="true|false" %> In JSP.3 Data conversion" for more information.RowSet. The property must be of the same type that the JSF component. a EL expression is like "${ }". It?s only in JSP 2. JSP and JSF used 2 differeents versions of EL.

Compound: expression ? val1 : val 2.name} To access method "checkLogin" of "person": #{person. For example. applicationScope A Map which map application attributes to their values. /. But you can also used Arithmetic: +. instanceof "empty" test if a value is null or if an array or a list is empty. Relational: ==.get(index)". this tag permit to declare the view which will contains the others tags. Examples: Access to property "name" of "person". <=. An array contains all values of a header. Object name cookie facesContext header headerValues initParam param paramValues requestScope sessionScope view Description A Map which map cookie values to a their values.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 #{person.get(key)" or null if the Map doesn?t contains the key.checkLogin} To access an array or a list. *. but it?s https://www.campus-booster.tab[2]} In this case expression "#{bean[property]}" is equivalent to "tab. "gt". The tag?s name is the same as the component without the "UI" prefix. the name of the property (or method) must be enclosed with quote. Example. >. For others exceptions. -. "eq". "lt".aspx?lecture=814&PM=True Page 59 of 100 . use operator "[]". JSF Taglibs Now we will study some useful tag in a JSF page. Root component of a JSF page. #{person['name']} Which is equivalent to: #{person. A Map which map request attributes to their values. They are always accessible with EL expression.checkLogin} Implicit objects They are implicits objects in JSF pages. It?s the simpler tag to display text.map['login']} Operator "[]" can also be used to access property or method. "ge". "and". Logical: &&. In this case. A Map which map request parameters to their values. For Map. A Map which map session attributes to their values. >=. #{person['checkLogin']} Which is equivalent to: #{person. if you want to get the value mapped to the key "login": #{uelBean. These operators can compare primitives and String. "ne". Operators Most of Java operators can be used. Table 4. !=. <f:view> <!--JSF tags --> </f:view> Simple text The <f:verbatim> tag generate an UIOutput component from its content. The tag?s name is the same as the component without the "Html" prefix. An array contains all values of a parameter. "div" and "mod". A Map which map init parameters to their values. use expression "#{bean['key?]}" is equivalent to "bean. an error is returned. A Map which map request parameters to their values. <. Every JSF component (not HTML) is a tag which is prefixed by default with a "f". you want to get the third element of an array: #{uelBean. !. "le".net/Booster/Pages/lectureSimpleViewer. ||. Every HTML component is a tag which is prefixed by a "h" by default.name} Call to method "checkLogin" of "person". Current FacesContext instance A Map which HTTP headers to their values. null is returned. A Map which HTTP headers to String array. JSF View The first tag that we have to use in JSF is <f:view>. "or" and "not". If exception IndexOutOfBoundsException is thrown.%.

nb}" /> </h:outputFormat> This example will display: Precision at 2 digits: 4. Only the text write in the tag can us CSS style. Example: <p> <f:verbatim>Hello Verbatim</f:verbatim> </p> 17/10/09 18:17 This example will generate this HTML code: <p>Hello Verbatim</p> Output components The tags which permit to display some text are: <h:outputText> <h:outputFormat> <h:outputLabel> They correspond to the components: HtmlOutputText HtmlOutputFormat HtmlOutputLabel They inherit from UIOutput which implement ValueHolder.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION not a specific HTML tag. Example of JSF code : <p> <h:outputFormat value="outputFormat is {0}"><br /> <f:param value="great" /> <!--Parameters--> </h:outputFormat> </p> This example generate this HTML code: <p>outputFormat is great</p> Other use: <h:outputFormat value="Precision at 2 digit: {0. It?s possible to transmit parameters on using under tag <f:param />.number.#.2 For more information. This attribute can be associated with a primitive.##}. a Number or every class which contains a data converter (Chapter "7. Note : It?s possible to display a text from a resource file (Chapter "8.aspx?lecture=814&PM=True Page 60 of 100 . Formatted output The <h:outputFormat> tag displays a formatted message with the format() method from the MessageFormat class.net/Booster/Pages/lectureSimpleViewer. It permts to affect a label to a input component like text field or a checkbox. at 1 digit: {0.#}"> <f:param value="#{basic.number.15. Label The <h:outputLabel> tag represent the <label> tag on HTML. The "for" attribute contains the id of the right label. Simple text The simpler tag to display a text in one line is: <p> <h:outputText value="text"/> </p> This tag will generate this HTML code: <p>text</p> Here is an other example but this time we will include some text in the tag. So it?s not possible to use every HTML attributes like the CSS style. look at the MessageFormat class documentation.3 Conversions").#. Example : <h:inputText id="address " value="your address here"> <!?text field > <h:outputLabel for="address " value="Address:" /> https://www.The "value" attribute permit to define the text to display.1 Internationalization). <p> <h:outputText value="Another test of " style="color: red"> outputText </h:outputText> </p> This example will generate this HTML code: <p>outputText <span style="color: red">Another test of </span></p> Graphically you?ll have: Note that the text in the tag is displayed before the text specify in the "value" attribute. a String. This tag is used like an under tag of the referenced tag.campus-booster. at 1 digit: 4.

The method used by the form is always "POST" and the encoding in " application/x-www-form-urlencoded". <h:inputTextarea cols="10" rows="10" /> This example generate this HTML code: <textarea cols="10" rows="10"></textarea> Password field The <h:inputSecret> permit to type a password. It means that every tags in a form must have an unique id.jsf" enctype="application/x-www-form-urlencoded"> <span id="_id1:name">text</span> <input type="hidden" name="_id1" value="_id1" /> </form> Every component which doesn?t have an id will have an attributed one.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 </h:inputText> This example will generate this HTML code: <label for="address">Address:</label> <input id="address" type="text" name="address" value="your address here" /> You can also use the <h:outputLabel> tag. Text field The simpler tag to type text is <h:inputText>. a String. Example : <h:outputLabel for="city" value="City:" /> <h:inputText id="city" value="Strasbourg" /> Here is what it will display with the 2 examples : Form This tag represents a form.jsf" enctype="application/x-www-form-urlencoded"> <input type="hidden" name="_id0" value="_id0" /> </form> A last example which illustrate how to add an id for every under tags of a form: <h:form> <h:outputText id="name" value="text" /> </h:form> In HTML: <form i d="_id1" method="post" action="/HW/04Form. <h:inputText maxlength="20" size="20" value="default value"/> This example will generate this HTML code: <input type="text" value="default value" maxlength="20" size="20" /> Multi lines text field The <h:inputTextArea> tag permit to type a text in few lines. The value can be linked to a primitive. <h:inputSecret redisplay="false" value="#{bean. (By default its value is false). It?s possible to use "required" attribute to indicate that a field is obligatory.net/Booster/Pages/lectureSimpleViewer.campus-booster. <form id="_id0" method="post" action="/HW/04Form.password}" /> The JSF code generate this HTML code: <input type="password" /> Hidden field https://www. The id used is prefixed by the id of the form. Example: <h:form> </h:form> JSF will add some information when the tag will be translated into HTML. The "redisplay" attribute permit to keep it when the page is reloaded. The "value" attribute of these tag permit to affect a value by default to a field. a Number or every class which have a data converter. It permits to give few times the same id in different form. Input components The components to type data: HtmlInputText HtmlInputTextarea HtmlInputSecret HtmlInputHidden They inherit of UIInput which implements EditableValueHolder.aspx?lecture=814&PM=True Page 61 of 100 . The component implements "NamingContainer".

jsf). With this kink of link you?ll be able to define the navigation of your web site in a configuration file. It extends UICommand which implement " ActionSource ". the link refreshes the current page.aspx?lecture=814&PM=True Page 62 of 100 .requestPathInfo}. a String.jsp JSF link You can create a link with " HtmlCommandLink ". mapping to the JSF Servlet.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 The <h:inputHidden> tag permit to include a hided field in a web page. See chapiter " 6.hide}"/> This JSF code generate this HTML code: <input type="hidden" value="value" /> Link It exist 2 kind of link in JSF: The simple links. which don?t start any event on the server side.requestContextPath = /JSFCourse facesContext.externalContext.jsp " is reachable through the url " http://localhost:8080/index.net/Booster/Pages/lectureSimpleViewer.requestContextPath}. if you have the URL " http://localhost:8080/JSFCourse/faces/testLiens. a Number or any other class with a converter (see chapter about converters). web site context #{facesContext. This string is empty if mapping use a suffixe (like *. a Number or every class which have a data converter. but a string value. The tag related to this component is <h:commandLink>. #{facesContext.externalContext. So. the HTML code will be: <a href="url">Text of the link</a> Every urls are relatives to the current url. It uses the "HtmlOutputLink" component which inherits of UIOutput which implements ValueHolder. Every links of your web site (which are linked to your web site) have to be the second type. The value can be associated to a primitive. for example : " index.requestServletPath}. path to the current web page.jsp " so you will retrieve the following values: facesContext.externalContext.2 Navigation " for further information about the action attribute and navigation rules.externalContext.requestPathInfo = /testLiens. starting from the JSF Servlet.jsp " " /index. The link which will start an event on the server side.externalContext.externalContext.jsp " It is possible to retrieve the web site context and mapping with the following expressions: #{facesContext. This one is evaluated inside JSF navigation rules which are defined inside its configuration (see faces-config. It is also possible to nest a <h:outputText> tag to define the displayed text: <h:form> https://www. For example. It?s possible to refer to the web site root on prefixing the url by "/". we have to use an under tag like <h:outputText>.jsp Where " JSFCours " is the web site context and " faces " is JSF file mapping. Exemple : <h:form> <h:commandLink action="success" value="This is a JSF link" /> </h:form> If no action attribute is defined.jsp " is reachable through the url " http://localhost: 8080/JSFCours/faces/index. The "value" attribute permit to define the url of the link. It doesn?t exist attribute which define the text of the link. a String. To define the text. Example : <h:outputLink value="url "> <h:outputText value="Text of the link" /> </h:outputLink> We can use few under tags to define the text: <h:outputLink value="url "> <h:outputText value="Text " /> <h:outputText value="of the " /> <h:outputText value="link" /> </h:outputLink> In the 2 cases. This tag has to be nested inside a <h:form> tag. <h:inputHidden value="#{bean.campus-booster. Simple link The <h:outputLink> tag permit to display a link. The value can either be a primitive. This kind of link does not use any URL to define destionation.xml file). Its " value " attribute allows to define its text (not destionation URL).requestServletPath = /faces facesContext. If we have the following url: http://localhost:8080/JSFCours/faces/testLiens. It will permit to manage the navigation of the web site with a unique file.

jsp"/> <f:param name="id" value="2"/> <f:param name="sortBy" value="price"/> </h:outputLink> <br/> <h:commandLink> <f:param name="id" value="6"/> <f:param name="sortBy" value="name"/> </h:commandLink> </h:form> They can be retrieved with the expression " #{param. It has a " layout " attribute which allow displaying value either: Horizontal side with " lineDirection " value Vertical side with " pageDirection " value.aspx?lecture=814&PM=True Page 63 of 100 .jsp"> <h:outputText value="index. It allows defining tags only if a parameter exists.sortBy}" /> You can test wether the parameter has been defined with the expression: " #{!empty param. which are " value " and " name " : <h:form> <h:outputLink value="index. you have to nest a <h:outputLabel> tag. sortBy=#{param.property}"/> Returned HTML code: <input id="choix" type="checkbox" /> To display a text close to the checkbox. Example: <h:selectBooleanCheckbox id="choice" value="#{bean. Example: <h:outputText value="(Only displayed if 'id' exists) id=#{param.. Parameters It is possible to define parameters inside a link by nesting <f:param> tags. <form method="post" action="/HW/06Liens. In order to define which boxes have to be displayed..jsf" enctype="application/x-www-form-urlencoded"> <a href="#">lien success</a> </form> . BooleanCheckbox Component The " value " attribute define wether the checkbox is displayed (or not). You can also define inside which boxes are selected by default (you will see that later). It is referenced by the "value" attribute. it is : <h:outputText value="id=#{param.id}"/> Button The component which display a button is " HtmlCommandButton ". You have to use the <h:selectManyCheckbox> tag.ParameterName} ". you have either to: nest <f:selectItem> tags or nest a single <f:selectItems> tag which need a reference with items from the managed-bean. It extends UICommand which implements ActionSource (and ActionSource2 for JSF 1. Example: <h:selectBooleanCheckbox id="choice" value="#{bean. In this case.2). you want to display many checkboxes in the same time to propose many choices.id}.id}" rendered="#{!empty param. It has two main attributes..SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <h:commandLink action="success"> <h:outputText value="This is a JSF link" /> </h:commandLink> </h:form> The two previous example render the following HTML code: . A button works almost like link.net/Booster/Pages/lectureSimpleViewer.property}"> <h:outputLabel for="choice" value="Married :" /> </h:selectBooleanCheckbox> ManyCheckBox component Most of the time. SelectItem https://www. It can only be a boolean value. Selected boxes can be saved inside a List or Array object.campus-booster.ParameterName} ". Example : <h:form> <h:commandButton action="action value" value="Send" /> </h:form> Below is the returned HTML code: <input type="submit" value="Send" /> Checkbox There are 2 components which display checkboxes: <h:selectBooleanCheckbox> only one checkbox <h:selectManyCheckbox> many checkboxes.

SelectItems You can also initialize your items directly from a ManagedBean containing an Array. } public void setAllCities(List allCities) { this. "Strasbourg :")).lang. Indeed.selectedCities = selectedCities. public Bean() { //add available cities allCities. "StrasbourgValue "). In this case. } public void setSelectedCities(List selectedCities) { this. "LyonValue "). If the user selects 2 boxes.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION The nested <f:selectItem> tag is a check box.selectedCities}"> <f:selectItems value="#{bean.add(new SelectItem("LyonValue". Its constructor has the following parameters: Group name Description Activation (false means disabled and true means enabled) A SelectItem array Once a SelectItemGroup instanciated. Example: Map allCityMap = new HashMap(). you have to use a converter.put("Lyon :". It is important to take care about the type of your objects on the ManagedBean side.String ".allCities = allCities.aspx?lecture=814&PM=True Page 64 of 100 . you can gather many groups and items inside a List as you can see on the following example: https://www. Its contains the "itemValue" of all the selected boxes.add("LyonValue"). but you can not use an array of integer because values are strings. } public List getSelectedCities() { return selectedCities. Finally.net/Booster/Pages/lectureSimpleViewer. "Lyon :")).campus-booster. by using the <f:selectItems> tag. } } Here. allCitiesMap. you can use a Map. allCitiesMap. Indeed. " #{bean.allCities}" /> </h:selectManyCheckbox> You can also use an array to save your cities: SelectItem[] allCities . allCities. If you want to create items with objects of your choice (like your own class City). You have to put your items inside a SelectItemGroup. Example: <h:selectManyCheckbox id="ville" layout="pageDirection" value="#{bean. items value is " java. } public void setSelectedCities(List selectedCities) { this. you can either use an array of String (String []) or a List to contains selected cties.add(new SelectItem("StrasbourgValue". //city selected by default selectedCities. the keys are the values. and values of the map are the displayed labels.selectedCities} " expression create a link with the selected cities.selectedCities"> <f:selectItem itemValue="StrasValue" itemLabel="Strasbourg" /> <f:selectItem itemValue="LyonValue" itemLabel="Lyon" /> <f:selectItem itemValue="ParisValue" itemLabel="Paris" /> </h:selectManyCheckbox> 17/10/09 18:17 It displays the following french cities: Below is the ManagedBean code: public class Bean { private List selectedCities = new ArrayList(). public List getSelectedCities() { return selectedCities.put("Strasbourg :". For example. Its attributes " itemValue " and " itemLabel " contain the value and the displayed text. How to gather items? It is possible to create SelectItem groups. JSF need a String value. thus " selectedCities " will contain " StrasValue ". } public List getAllCities() { return allCities.selectedCities = selectedCities. when the user sends a form with the " Strasbourg " city selected. } } Then you reference your ManagedBean inside a <f:selectItems> tag: <h:selectManyCheckbox id="ville" value="#{bean. " selectedCities " will contain " StrasValue " and " LyonValue ". private List allCities = new ArrayList(). a Map or a List. Let?s take the following class as ManagedBean: public class Bean { private List selectedCities = new ArrayList().

<h:selectManyListbox> display a multiple choice list (it works the same way as <h:selectManyCheckBox>). //create a group for French cities SelectItemGroup franceGroup = new SelectItemGroup("France". Example: <h:selectOneMenu id="city" value="#{bean. citiesFrance[2] = new SelectItem("ParisValue". germanyCities[0] = new SelectItem("KehlValue".campus-booster. allCities.aspx?lecture=814&PM=True Page 65 of 100 . citiesFrance[0] = new SelectItem("StrasValue". citiesFrance). " #{bean. Above.add(germanyGroup).add(franceGroup). "Berlin :"). a String. It is very similar as <h:selectOneRadio> tag (see chapter " 5.2 MultipleCheckbox component " for more information about these tags). "Strasbourg"). List There is 2 components to display a list: <h:selectOneListbox> to display a list with only one item selected in the same time (it works the same way as <h:selectOneRadio>). allCities.8. false. Example: <h:selectManyListbox id="color" value="#{bean. a Number or any class having a converter.selectedCities}"> <f:selectItems value="#{bean. The " size " attribute allows you to define how many lines you want to display. allCities.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 // city list List allCities = new ArrayList(). citiesFrance[1] = new SelectItem("LyonValue". Example: <h:selectOneRadio layout="lineDirection" value="#{bean. "Lyon :"). // create a group for german cities SelectItemGroup germanyGroup = new SelectItemGroup("Allemagne".color} " is a String because values are Strings. SelectItem london = new SelectItem("LondresValue". "Paris :"). //french cities SelectItem[] citiesFrance = new SelectItem[3]. It use the class " HtmlSelectOneRadio " which implement " EditableValueHolder ". "Londres :"). The radio button selected can either be stored as a primitive.add(london).color}> <f:selectItem itemValue="red" itemLabel="red"/> <f:selectItem itemValue="white" itemLabel="white"/> <f:selectItem itemValue="yellow" itemLabel="yellow"/> </h:selectOneRadio> The property referenced by the " value " attribute should have the same type as the item value.net/Booster/Pages/lectureSimpleViewer. A list is constructed with nested <f:selectItem> tags or a single <f:selectItems> tag (see chapter " 5.allCities}" /> </h:selectOneMenu> Pictures https://www. "French cities".9 RadioButton " for further information). //german cities SelectItem[] germanyCities = new SelectItem[2]. false. germanyCities). "Kehl :"). "German cities". It displays the following page: RadioButton The <h:selectOneRadio> tag allows defining a radio button list.colors}"> <f:selectItem itemValue="red" itemLabel=" Red:"/> <f:selectItem itemValue="white" itemLabel=" White:"/> <f:selectItem itemValue="yellow" itemLabel=" Yellow:"/> </h:selectManyListbox> Below is the result: <select id="color" size="3"> <option value="rouge">Red:</option> <option value="blanc">White:</option> <option value="jaune">Yellow:</option> </select> Combo Box A Combo box is created by the <h:selectOneMenu> tag. germanyCities[1] = new SelectItem("BerlinValue". Notice that only one button can be selected at the same time.

if you do not use it.1. then CSS classes groups are reused for the following columns. you have to put a space between each one: class1. Indeed.1 " for the second " class3 " for the third " class4.net"><img src="java. Indeed.2 class1. When you use this table.3 . Example: <h:panelGroup> <h:outputText value="first child" /> <f:verbatim><br /></f:verbatim> <h:outputText value="second child" /> </h:panelGroup> It returns the following HTML code: first child<br />second child Notice the <f:verbatim> tag around <br/>. class2 class2. and it works the same way. Static table: PanelGrid This kind of array is created with the <h:panelGrid> tag. If there is not the same number of CSS classes groups and columns: If there are more columns than CSS classes groups. " class1.net/Booster/Pages/lectureSimpleViewer. you have to use a comma: class1. https://www. It has the following attributes: " url ". some components can only have one nested tag.1 class1. a description of the picture <h:graphicImage url="URL to the picture" alt="description"/> 17/10/09 18:17 You can also use pictures as links by nesting a <h:graphicImage> tag inside a link component: <h:outputLink value="http://java.2 class1.2 In this case. it does not fit well with dynamically generated tables..aspx?lecture=814&PM=True Page 66 of 100 . It allows returning the text and tags in the same postition.1 class1.2 " and " class1.3..jpg" alt="" />java. class4 class4..2 " for the fourth. useless CSS classes groups won?t be used.. has 4 columns CSS classes " class1.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION The <h:graphicImage> tag allows to insert a picture..jpg" /> <h:outputText value="java.campus-booster.net"> <h:graphicImage value="javadotnet..net</a> Panel The <h:panelGroup> tag allows gathering many JSF components in order to handle them as only one tag.1 ". The " rowClasses " attribute allows defining CSS classes to lines. To declare CSS classes for each column. Indeed.1 class 4. class3. the path to the picture " alt ". If there are less columns than CSS classes groupes. it means you already know how many lines and rows you want to display.1 " and " class4.2): The " columnClasses " attribute allows defining CSS style listing for each column. the table.3 " are used for the first column " class2 " and " class2.: <h:panelGroup> <h:outputText value="first child" /> <br /> <h:outputText value="second child" /> </h:panelGroup> You could have the following result: <br />first childsecond child Table There is two ways to create tables with JSF: <h:panelGrid> <h:dataTable> They both have the following attributes: footerClass: define which CSS class(es) are used to display the table?s footer headerClass: define which CSS class(es) are used to display the table?s header captionClass (only with JSF 1. In order to define CSS classes for a column.net" /> </h:outputLink> Below is the result: <a href="http://java.

if it is a header " footer ". if it is a title (only with JSF 1. It has an attribute called " name " which define which part is currently written.aspx?lecture=814&PM=True Page 67 of 100 . if you want to display 3 columns. As there are 2 columns. you have to nest tags inside. a new line will be created for each after 3 tags: <h:panelGrid border="1" columns="3"> <h:outputText value="A" /> <h:outputText value="B" /> <h:outputText value="C" /> <h:outputText value="D" /> </h:panelGrid> It displays the following table: Table 2. Available values are the following ones: " header ". Example: <h:panelGrid border="1" columns="2" rules="all"> <f:facet name="header"> <h:outputText value="I am the header!" /> </f:facet> <f:facet name="footer"> <h:panelGroup> <h:outputText value="I am the " /> <h:outputText value="footer" /> </h:panelGroup> </f:facet> <!--do not work with JSF 1. A B C D Group elements If you want to use many tags inside the same cell. you have to use the <h:panelGroup> tag to nest many tags. JSF define the position of each component according the order in which it is declared. we can assume there is 2 lines.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION In order to define the content of a table. A B C D Now.net/Booster/Pages/lectureSimpleViewer.2) The <f:facet> tag do not have any child tag. Example: <h:panelGrid border="1" columns="2"> <h:outputText value="A" /> <h:outputText value="B" /> <h:outputText value="C" /> <h:outputText value="D" /> </h:panelGrid> 17/10/09 18:17 We described the cells starting from upper left to bottom right. Example: <h:panelGrid columns="2" border="1" rules="all"> <h:outputText value="A" /> <h:panelGroup> <h:outputText value="B" /> <f:verbatim><br /></f:verbatim> <h:outputText value="B bis" /> </h:panelGroup> <h:outputText value="C" /> <h:outputText value="D" /> </h:panelGrid> The following code is generated: <table border="1" rules="all"> <tbody> <tr> <td>A</td> <td>B<br />B bis</td> </tr> <tr> <td>C</td> <td>D</td> </tr> </tbody> </table> Header and footer A header or a footer is defined with a <f:facet> tag. There is no tag which defines the beginning or the end of a line. if it is a footer " caption ".1--> <f:facet name="caption"> https://www. It displays the following table: Table 1. and 4 components. you have to group them inside the <h:panelGroup> tag.campus-booster.

sql.property1" /> </h:column> <h:column> <%--second column--%> <h:outputText value="#{itemFromTheList . headers. Indeed.servlet. you have to use the <h:column> tag. thou the table display five lines.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <h:outputText value="caption" /> </f:facet> <h:outputText value="A" /> <h:outputText value="B" /> <h:outputText value="C" /> <h:outputText value="D" /> </h:panelGrid> Below is the returned HTML code: <table border="1" rules="all"> <thead> <tr> <th colspan="2" scope="colgroup">I am the header </th> </tr> </thead> <tfoot> <tr> <td colspan="2">I am the footer</td> </tr> </tfoot> <tbody> <tr> <td>A</td> <td>B</td> </tr> <tr> <td>C</td> <td>D</td> </tr> </tbody> </table> Below is a screenshot Dynamic table: DataTable The <h:dataTable> tag allows to generate a table dynamicaly.campus-booster.ResultSet A javax. Each one set a new column : <h:dataTable value="#{bean.DataModel A java.aspx?lecture=814&PM=True Page 68 of 100 . it browses elements like the following ones: A JavaBean list A JavaBean array A JavaBean A javax. You can also use the following attributes: " first " to define the first displayed element " rows " to define how many elements to display Header and Footer Like PanelGrid table.ResultSet A javax. footers and titles are defined with <f:facet> tag by nested the <f:facet> tag inside a <h:column> tag.property2}" /> </h:column> </h:dataTable> If the list contains five elements.net/Booster/Pages/lectureSimpleViewer.elementList}" var="itemFromTheList" /> To define the content of the table.faces.model. Below is an example: <h:dataTable value="#{bean.jsp.sql.myList}" var="item"> <h:column> <f:facet name="header"> <h:outputText value="Property 1" /> https://www. Furthermore.elementList}" var="itemFromTheList" /> <h:column> <%--first column--%> <h:outputText value="#{itemFromTheList .RowSet The " value " attribute allows defining which property to browse.sql.jstl. Example: <h:dataTable id="items" value="#{bean. " var " attribute is the name which references the elements of the " value " attribute.

labosun.createStatement().personRS}" var="personDB" rules="all" border="1"> <h:column> <f:facet name="header"> <h:outputText value="Name" /> </f:facet> <!-.property1 }" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Property 2" /> </f:facet> <h:outputText value="#{item . when an instance is created. inside the JSF "faces-config. Statement st = cnx.Driver"). "pass").Retrieve lastname column --> <h:outputText value="#{personDB['lastName']}" /><br /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Prénom" /> </f:facet> <!-.executeQuery("select * from contact"). } catch (Exception e) { // exception handling (not described here) } } } Here we declare a bean.aspx?lecture=814&PM=True Page 69 of 100 .net/Booster/Pages/lectureSimpleViewer. Connection cnx = DriverManager.xml" configuration file: <managed-bean> <managed-bean-name>dbBean</managed-bean-name> <managed-bean-class>com.campus-booster.forName("com.personRS = st. error message " SEVERITY_FATAL ". which are either specific or global: The <h:message> tag display a message. Example: package com. Indeed. It is displayable inside with <h:message> and <h:messages> tags. warning message " SEVERITY_ERROR ". For the moment. public class DataBaseBean { private ResultSet personRS.newInstance().DataBaseBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> Then.firstName}" /> </h:column> </h:dataTable> Error messages When an error append (empty text field.getConnection("jdbc:mysql://localhost/jsfCours". etc.Retrieve firstname column --> <h:outputText value="#{personDB.2 Messages management ". fatal message (high importance) There are 2 kinds of message. we will only see to display them. Attribute Type Default value Description https://www. The <h:messages> tag allows displaying all the messages.personRS = personRS. This feature is described in the chapter " 8. a simple " SELECT " request is executed over a table. this. the following JSF code uses the ResultSet with <h:dataTable> tag and its "value" attribute: <h:dataTable value="#{dbBean. It?s " for " attribute allows defining which comonent it is related to.jdbc. "login".property2 }" /> </h:column> <f:facet name="footer"> <h:outputText value="I am a footer!"/> </f:facet> </h:dataTable> Example: Display a database table Let?s finish by an exemple which display a database table inside a JSF table ! We start by writing a JavaBean which read the database content.mysql. } private void initConnection() { try { Class. conversion error. } public void setPersonRS(ResultSet personRS) { this.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 </f:facet> <h:outputText value="#{item . information message (low importance) " SEVERITY_WARN ".) a message is created. These tags have the two following attributes: Table 3. } //Getter and setter public ResultSet getPersonRS() { return personRS. public DataBaseBean() { initConnection(). Messages have different importance levels: " SEVERITY_INFO ".labosun. Then we will display it inside a <h:dataTable> tag.

17/10/09 18:17 showSummary boolean true The <h:messages> tag has also the following ones: Table 4. fatalClass CSS class used for " FATAL " level messages.0' encoding='UTF-8'?> <faces-config xmlns="http://java. There is also the " errorStyle ".com/xml/ns/javaee/web-facesconfig_1_2.sun.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.com/xml/ns/javaee" xmlns:xsi="http://www. You can also change the CSS class of your messages : Table 5.net/Booster/Pages/lectureSimpleViewer. Server configuration JSF configuration is set into the " WEB-INF/faces-config. Available scope values are the following: " application " means your JavaBean instance is reachable for all the users. " managed-bean-scope " define the scope of your JavaBean (either request. session. infoClass CSS class used for " INFO " level messages.sun.0//EN" "http://java. the file looks like this: <?xml version='1. The template of this file is: <?xml version="1.sun.xsd" version="1.//DTD JavaServer Faces Config 1. JavaBeans declaration To configure JavaBeans and handle them through JSF pages. Indeed a message is displayed if the value is not validated.0"?> <!DOCTYPE faces-config PUBLIC "//Sun Microsystems. below is the appropriate declaration: <managed-bean> <managed-bean-name>nom du bean dans la page JSF</managed-bean-name> <managed-bean-class>class du bean </managed-bean-class> <managed-bean-scope>(application|session|request|none)</managed-bean-scope> <managed-property> <property-name>nom de la propriété </property-name> <property-class>type de la propriété </property-class> <value>valeur par défaut </value> </managed-property> </managed-bean> " managed-bean-name " is the JavaBean name to reference it from JSF pages. " managed-bean-class " is the fully qualified name of the JavaBean class.com/dtd/web-facesconfig_1_1. Name Description errorClass CSS class used for " ERROR " level messages. Attribute Type Default value Description Define wether the tag display only global messages (true) or all the messages (false). Inc. application or none). " managed-property " initialize a property of your managed bean.2"> </faces-config> Nested tags allow configuring JSF. https://www.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION showDetail boolean false Define wether more information is displayed. Define wether a summary is displayed. " fatalStyle ".aspx?lecture=814&PM=True Page 70 of 100 .w3.dtd"> <faces-config> </faces-config> With JSF 1.sun. " infoStyle " and " warnStyle " attributes to define directly the style.com/xml/ns/javaee http://java.xml " file.2.campus-booster. warnClass CSS class used for " WARN " level messages. It allows defining a specific renderings: layout String list " list " to display messages in a HTML list " table " to display messages in a HTML table globalOnly boolean false Example: <h:inputText id="number"> <f:validateLongRange minimum="1" maximum="10" /> </h:inputText> <h:message for="number"/> <h:commandButton id="submit" action="success"/> The <f:validateLongRange> tag allows testing if value is between 1 and 10.

https://www. Example: Declaration of a SelectItem list We already have declared collections.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION " session " means your JavaBean instance is specific for each user.util. let?s see about SelectItem list.SelectItem class --> <managed-bean-class>javax. Map declaration A "Map" is declared with a <map-entries> tag. it is possible to define a null value with the <null-value> tag. Finally.ArrayList</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <list-entries> <value-class>java. They are both nested inside the <map-entries> tag..value</value-class> <!--first entry --> <map-entry> <key>value of the key 1</key> <value>value associatied with key 1</value> </map-entry> <!--second entry --> <map-entry> <key>value of the key 2</key> <value>value associated with key 2</value> </map-entry> </map-entries> </managed-bean> Just as list declaration.util.SelectItem</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <managed-property> <property-name>value</property-name> <value>Lyon</value> </managed-property> <managed-property> <property-name>label</property-name> <value>Lyon</value> </managed-property> </managed-bean> Then you declare another managed bean with the ArrayList class and entries made of previously declared "city0" and "city1" managed beans. We first created managed beans with the SelectItem class and entries within: <!--declare a first bean --> <managed-bean> <managed-bean-name>city0</managed-bean-name> <!--this bean is a javax.String</value-class> <value>Strasbourg</value> <value>Bordeaux</value> <value>Paris</value> <value>Nice</value> <null-value/> </list-entries> </managed-bean> 17/10/09 18:17 Notice you can include a null value thank to the <null-value> tag.lang. The <key-class> and <value-class> tags define which class to use as key and value.HashMap</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <map-entries> <key-class>type.your.aspx?lecture=814&PM=True Page 71 of 100 .model. you can define which class to use.class</key-class> <value-class>type. " request " means a JavaBean instance is created for each request. you have to insert a <map-entry> tag. Example: <managed-bean> <managed-bean-name>cityList</managed-bean-name> <managed-bean-class>java. This last one has two nested elements which are <key> and <value>.of.your. Then you nest values with <value> tags.campus-booster. " none " means a JavaBean instance is created each time it is called.. .of. For each entry in the map.SelectItem</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <!--we define below two entries --> <managed-property> <property-name>value</property-name> <value>Stras</value> </managed-property> <managed-property> <property-name>label</property-name> <value>Strasbourg</value> </managed-property> </managed-bean> <!--declare a second bean --> <managed-bean> <managed-bean-name>city1</managed-bean-name> <managed-bean-class>javax.faces.model. List declaration A list is declared with the <listentries> tag. Example: <managed-bean> <managed-bean-name>dicoMap</managed-bean-name> <managed-bean-class>java. You can also define which class to use with the <value-class> tag.faces.net/Booster/Pages/lectureSimpleViewer.model.faces. now.

Global mapping It is also possible to define a navigation rule for all your application with the "/*" value as source value. Another solution is to remove the <from-view-id> tag. They can be used alone or in the same time. Then we can nest as many " navigation-case " as needed and each one have an "outcome" string and "destination" page. https://www. Each rules define sources and destinations pages. you are creating a navigation rule for the web page "index. inside "web. which are <from-action> and <from-outcome>.jsp</to-view-id> </navigation-case> </navigation-rule> As you can see above.xml" file: <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*. Indeed there is three ways to declare navigation rules: If you only write out the " from-outcome " tag. There is two main tags.aspx?lecture=814&PM=True Page 72 of 100 . all the pages which returns "error" shall forward the user to the web page "error. navigation is true. If you only write out the " from-action " tag. this syntax is a bit heavy. then the user is being forwarded to " buy.model.ArrayList</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <list-entries> <value-class>javax. Action strings Let?s look a bit further about navigation. The " from-outcome " tag is the string returned by a link.jsf</url-pattern> </servlet-mapping> Let?s now explore a bit more use cases. Take the following example: <navigation-rule> <from-view-id>/index. Finally the " to-viewid " tag is the destination page. Whatever the return value is. If you write out the two of them. the value should be a reference to a method. a managed bean method. You have to use "/? as the beginning of the URL to refer to the root of the web site. a button.net/Booster/Pages/lectureSimpleViewer. You can insert actions into your web pages with JSF tags and their "action" attribute: Action example with a link: <h:form> <h:commandLink action="success" value="Make an order"/> </h:form> Action example with a button: <h:form> <h:commandButton action="success" value="Make an order"/> </h:form> Notice that this declaration works well with the two following JSF declaration. Example: <navigation-rule> <from-view-id>/*</from-view-id> <navigation-case> <from-outcome>error</from-outcome> <to-view-id>/error.jsp". the string must be equal either to an action attribute value or the return value of a method.jsp ".jsp</to-view-id> </navigation-case> </navigation-rule> In this case.faces. etc.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/buy. <navigation-rule> <from-view-id>/source page</from-view-id> <navigation-case> <from-outcome>string returned by an action</fromoutcome> <to-view-id>/destination page</to-view-id> </navigation-case> </navigation-rule> The " from-view-id " tag defines the source page.campus-booster.util.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <!--Déclaration de la liste --> <managed-bean> <managed-bean-name>villes</managed-bean-name> <managed-bean-class>java. Navigation Navigation is defined with "navigation rules". and it is shorted to write entries directly. naviguation would only be true if the method defined inside " from-action " returns the value specified inside the " from-outcome " tag.jsp". If an action return the value "success".SelectItem</value-class> <value>#{city0}</value> <value>#{city1}</value> </list-entries> </managed-bean> As you can see.

If the method returns any other string than "order" or "mustLogin". write out the following component: <h:commandLink action="#{bean.campus-booster. Then.method}" value="Vers la page xxx"/> Let?s take a full example ? first we define the following rule: <navigation-rule> <from-view-id>/index. } else { return "mustLogin". you have to use an action attribute with a reference to a method. You can also call a method from a managed-bean and analyse its return value.jsp ": <h:form> <h:commandLink value="Vers la page achat" action="#{navi. then a method from a managed-bean returns " success "..SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Currently used action strings in " from-outcome " are the following: Table 1.jsp</to-vie-wid> </navigation-case> <navigation-case> <from-action>#{navi.jsp</to-view-id> </navigation-case> </navigation-rule> . the user is not redirected and he stays on the same page. } } . From-outcome It is the tag we used in the previous examples.validateOrder} </from-action> <from-outcome>mustLogin</from-outcome> <to-view-id>/login.jsp</to-view-id> </navigation-case> </navigation-rule> We used <from-action> twice but the value nested inside <from-outcome> will allow to create different navigation cases...aspx?lecture=814&PM=True Page 73 of 100 . Signification 17/10/09 18:17 no results Research did not return any result. if( choice == 0) { return "order". Return to the search form. int choice = r. } } } From-action With this tag.validateOrder}"/> Here a example of method you could write: public class NaviBean { public String valideAchat() { Random r = new Random().getSuccessString}"/> </h:form> Notice: "navi" is the name of our managed-bean. you only specify which method to use: <navigation-rule> <from-view-id>/index.net/Booster/Pages/lectureSimpleViewer. public class NaviBean { public String getSuccessString() { return "success".jsp</fro-mview-id> <navigation-case> https://www. and finally we write out the JSF link component in the page " index.nextInt(2). Outcome success failure logon It worked correctly Error during page rendering User should be redirected to login page.validateOrder} </from-action> <from-outcome>order</from-outcome> <to-view-id>/order. like displayed below: <h:commandLink value="Valide les achats" action="#{navi.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/achat. Below is a method example: public String methodName().. From-action and from-outcome Let?s illustrate " from-action " and " from-outcome " with the following example: <navigationrule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-action>#{navi. In order to use this navigation case.

} // Getters and setters . elements.jsp" page.jsp</to-view-id> </navigation-case> </navigation-rule> Above. // used during entries handling /** * Initialize an entries list with default values */ public NaviExempleBean() { this. and add it to the list. It also displays links to the list and delete page.jsp " allows to create a new entry inside the list. it displays a confirmation message and redirect the client to the list page.jsp " allows to remove an entry.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/delete. " new.jsp</to-view-id> </navigation-case> <navigation-case> <!--link with the list page > <from-outcome>list</from-outcome> <to-view-id>/list. Elle possède un lien vers la page principale. Below are navigation rules: <navigation-rule> <from-view-id>/list.aspx?lecture=814&PM=True Page 74 of 100 .jsp</from-view-id> <navigation-case> <!--link with the detail page > <from-outcome>edit</from-outcome> <to-view-id>/edit. " delete. elements. you have to pass the entry parameter inside the request. /** * Create a new entry.add("tomato").SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <from-action>#{navi.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/new..add("ham"). When you want to remove an entry.jsp</from-view-id> <navigation-case> <!--link with the main page > <from-outcome>success</from-outcome> <to-view-id>/list. whatever the return value is.jsp</from-view-id> <navigation-case> <!--link with the creation page > <from-outcome>success</from-outcome> <to-view-id>/list.valideOrder}" /> Example Let?s finish this chapiter by a comprehensive example of navigation rules. Below is an action attribut which call the validateOrder() method: <h:commandLink action="#{navi.elements = new ArrayList<String>().3 Parameters ".jsp " displays all the information of an entry. It also displays links to remove and modify them.campus-booster. elements.jsp</to-view-id> </navigation-case> </navigation-rule> Below is the managed-bean that you will use: public class NaviExampleBean { private List<String> elements.add("potato"). https://www. // a list with entries private String newElt. as you saw on the chapter " 5.6. it displays all the entries of the list.add("salad").. elements.jsp</to-view-id> </navigation-case> <navigation-case> <!--link with the remove page > <from-outcome>delete</from-outcome> <to-view-id>/delete. " detail. Indeed you have to write a managed-bean with a List<String> typed object.jsp</from-view-id> <navigation-case> <!--link with the delete page > <from-outcome>delete</from-outcome> <to-view-id>/delete. elements.net/Booster/Pages/lectureSimpleViewer.validateOrder}</from-action> <to-view-id>/order.jsp " is the main page.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/edit. This web site is composed of the following pages: " list.add("peach"). the user returns to the "order.jsp</to-view-id> </navigation-case> <navigation-case> <!--link with the creation page > <from-outcome>new</from-outcome> <to-view-id>/new. The purpose of the following web site is to manage a list.

*/ public String delete() { String element = FacesContext. } FacesContext.remove(element).getCurrentInstance().getRequestParameterMap().addMessage(null.getExternalContext().SEVERITY_INFO. } } /** * Remote the entry whom value is equal to the parameter "idElt". return "success".get("idElt"). */ public String create() { if (newElt != null) { this. FacesMessage fm.campus-booster.aspx?lecture=814&PM=True Page 75 of 100 . "Remove failed".SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 * @return success if it complete or failure else. return "success". * @return success when it complete.jsp " page: <f:view> <h:form> <!-.add(newElt). } } And its declaration <managed-bean> <managed-bean-name>naviEx</managed-bean-name> <managed-bean-class>com. fm = new FacesMessage(FacesMessage.send the parameter idElt to the delete page > <f:param name="idElt" value="#{elt}" /> </h:commandLink> </h:column> <h:column> <!-.you retrieve the idElt parameter and display the related entry --> <h:outputText value="More information about #{param['idElt']}" /><br /> <h:commandLink value="Remote this entry" action="delete"> <f:param name="idElt" value="#{param['idElt']}" /> </h:commandLink> <h:commandLink value="Return and cancel" action="list" /> </h:form> </f:view> Below is the result: https://www.NaviExampleBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> " list.we pass the parameter idElt inside the edit page --> <f:param name="idElt" value="#{elt}" /> </h:commandLink> </h:column> </h:dataTable> <h:commandLink value="Create a new entry" action="new" /> </h:form> </f:view> You can see below its display: " edit. } else { fm = new FacesMessage(FacesMessage.getCurrentInstance() .elements.jsp " page: <f:view> <h:form> <h1>Liste</h1> <!--allows to display error messages --> <h:messages /> <h:dataTable value="#{naviEx.net/Booster/Pages/lectureSimpleViewer.SEVERITY_INFO.elements}" var="elt" rules="all" border="1"> <h:column> <f:facet name="header"> <h:outputText value="Name" /> </f:facet> <h:outputText value="#{elt}" /> </h:column> <h:column> <!-. } else { return "failure". if (element != null) { elements.labosun. "Remove complete".Link to edit --> <h:commandLink value="edit" action="edit"> <!-. newElt = null. fm). "").link to delete --> <h:commandLink value="Delete" action="delete"> <!-. "").

aspx?lecture=814&PM=True Page 76 of 100 . The event is treated server side. Attention however. Behavior ActionListener All the components which implement "ActionSource" (UICommand) can generate an event. javax.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 " new. separated by a comma. By default. xml " file.STATE_SAVING_METHOD " server ".create}" /><br /> <h:commandLink value="Cancel" action="success" /> </h:form> </f:view> Below is the rendering: " delete. the event is treated during the phase "Request parameters appliction".DEFAULT_SUFFIX javax.LIFECYCLE_ID Define which files. data is saved on the client side.net/Booster/Pages/lectureSimpleViewer. because during this phase.jsp " page: <f:view> <h:form> <h1>New entry</h1> <h:inputText id="name" value="#{naviEx. data is saved inside the user session " client ". The elements update order is the order of the tag declaration.xml" file.you pass the parameter idElt to inform the managed-bean which entry remove --> <f:param name="idElt" value="#{param['idElt']}" /> </h:commandLink> <h:commandLink value="No" action="success" /> </h:form> </f:view> Context parameters You can configure JSF through its context parameters in the "web. the value is " . By default. Second is to create an implementation of the interface "ActionListener". Here for recall the cycle of life of a JSF request : The events of type ActionListener are treated during the phase "Invocation of the application". Default extension of JSF pages. Generic method https://www.newElt}"> <h:outputLabel for="name" value="Name:" /> </h:inputText> <h:commandButton value="Validate" action="#{naviEx.jsp " Allows to define which class manage the life cycle of JSF. all the elements are not yet up to date (the javabeans are only updated during the phase "Update model"). when the client sends the page to the server.faces.jsp " page: <f:view> <h:form> <!-. <context-param> <param-name>Parameter name</param-name> <param-value>Parameter value</param-value> </context-param> Below are common parameters: Table 2. The first solution is to associate a method of a generic JavaBean.You retrieve idElt to known which entry remove --> <h:outputText value="Do you want to remove the entry: #{param['idElt']} ?" /> <h:commandLink value="Yes" action="#{naviEx.faces.faces.DEFAULT_LIFECYCLE Allows to define which facility save data.delete}"> <!-. as hidden fields. configure the JSF container. There are 2 manners of dealing with server side events.CONFIG_FILES javax. There are two available values: javax. The default value is: LifecycleFactory.faces. The default value is " server ". JSF only look inside the " faces-config.campus-booster. This means a method is called when the user clicks on an element. If the component which declares the event has the attribute "immediate" set to true.

17/10/09 18:17 The method can be in any bean. If the component which declares the event has the attribute "immediate" set to true. Example: <h:inputText value="value"> <f:valueChangeListener type="listeners.BeanValueChangeListener" /> </h:inputText > Data conversion The JSF components which implement ValueHolder (all the child classes of UIOutput) have a value.EventHandling" /> </h:commandLink> ValueChange Listener The components which implement "EditableValueHolder". because during this phase.faces.faces. When the page is sent to the server. all the modified values are generating a server side event.faces. To use the method you only have to refer to it by using the attribute "actionListener". https://www. It is possible to use the attribute "actionListener" as mentioned previously. There is just the method "processEvent (ActionEvent)" to implement.aspx?lecture=814&PM=True Page 77 of 100 .ValueChangeListener" and to redefine the method "processValueChange (ValueChangeEvent)". public class EventHandling implements ActionListener { public void processAction(ActionEvent actionEvent) { // Event handling } } This ActionListener can be referred in 2 different ways.event. This value can be a date. it is necessary that it has the following prototype : public void methodName(javax. the event is treated during the phase "Request parameters application". In that case.campus-booster. an email. UISelectMany. public class BeanValueChangeListener implements ValueChangeListener { public void processValueChange(ValueChangeEvent event) { // event handling } } This listener can be referred either thanks to the attribute "valueChangeListener" as seen previously. either thanks to the tag <f:valueChangeListener>.ActionListener".ActionEvent e). not all the elements are yet up to date (the javabeans are only updated during the phase "model update"). UISelectOne) have a value which can be edited by the user. The "type" attribute of this one makes it possible to specify the class of the used listener.e. The JavaBean which declares the method must be referred as JavaBean managed by the container. But we can also use the tag <f:actionListener>.event.faces. Here for recall the cycle of life of a JSF request: The events of type ValueChangeListener are treated during the phase "Validation of the user entries". Example: <h:commandButton value="Send" actionListener="#{beanName.net/Booster/Pages/lectureSimpleViewer. The method can then be referred thanks to the attribute "valueChangeListener". The elements update order is the order of the tag declaration. The "type" attribute of this tag makes it possible to specify the class of the used ActionListener. Example: package listeners.vent. all the child classes of UIInput (UISelectBoolean. The management of this event is similar to ActionListener. Example : package listeners. <h:inputText valueChangeListener="#{beanName. This transformation is necessary.methodName}" /> ValueChangeListener Interface The other solution consists in implementing "javax. ? There are no restrictions on the value which can be associated to a component under condition that the value can be converted form an Object into a String and conversely.methodName}" /> ActionListener interface It is also possible to create a class which implements "javax. all the conversion operations and validations related to this component will be carried out before the ValueChangeListener management. Example: <h:commandLink value="with an interface"> <f:actionListener type="listeners. i. but it must be referred as a managed bean by the container. Generic method A method which manages the event must have the following prototype: public void check(javax.ValueChangeEvent event). Be careful however.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION To create a method which manages an event. a number.vent.

For example a date canbe posted in the format "DD/MM/AAAA" or with the day in full letters. The values are: date (by default). The values are: default. short. medium.date}"> <f:convertDateTime dateStyle="full" /> </h: inputText > Now let?s see an example of a form which makes it possible to seize a date in the format "dd/mmyy" and which then transforms the string in a Date object. 2006. Description Code ISO4217 used for monetary conversions maxFractionDigits int minFractionDigits int maxIntegerDigits int minIntegerDigits type int String https://www. The local to represent the number. The tag <f:convertDateTime> has the following attributes: Table 1. Attribute currencyCode currencySymbol locale integerOnly Type String String String or Locale boolean Monetary symbol. 17/10/09 18:17 This principle of conversion also makes it possible to personalize the posting of the objects. Number All the conversion operations are carried out at the time of the phase "Request parameters application". Minimum number of digits after the comma. The values are: default.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION because during the phase "Request parameters application". JSF manages the conversion of the primitives and the standard objects of Java: Boolean. currency. If this attribute is defined. Allows specifying if the value to be represented is a date. Maximum number of digits before the comma. it is used instead of dateStyle and timeStyle. The conversions errors can be posted with the tag <h:message>. In our case it is "dd/MMyy": <h:form> <h:inputText id="date" value="#{bean. short.aspx?lecture=814&PM=True Page 78 of 100 . time and both. Defines what the number represents. If "true" only the whole part of the number will be considered. the object must be translated into a String. the JSF Servlet must be able to rebuild the object which represents the value of the client request (which is in the form of a String). This tag has the following attributes : Table 2. Standard conversion: Date The tag <f:convertDateTime> ensures the conversion Date String. TimeZone String String Allows defining a personalized date format. medium. long et full For the date Saturday 22th july 2006 the different values are: default: " Sat Jul 22 13:05:30 CEST 2006 " dateStyle String short: " 22/07/06 " medium: " 22 juil. a time or both. 2006 " long: " 22 juillet 2006 " full: " samedi 22 juillet 2006 " timeStyle String locale timeZone pattern type Defines the time format. Example: <h:inputText value="#{bean. Maximum number of digits after the comma. percentage.date}"> <h:outputLabel for="date" value="Date (dd/mm/yy): " /> <f:convertDateTime pattern="dd/MM/yy" /> </h:inputText> <h:commandButton value="valider" /> </h:form> Standard conversion : Number The tag <f:convertNumber > ensures the conversion Number String. For that it is necessary to use the attribute "pattern" and to define the date format to be used. Minimum number of digits before the comma. a date is posted in a following way: "Sat Jul 22 12:56: 12 CEST 2006" what corresponds to Saturday July 22. Attribute Type Description Defines the date format. It is necessary to use a pattern which is defined in the documentation of the class "SimpleDateFormat"of J2SE.net/Booster/Pages/lectureSimpleViewer. at the time of the return phase. By default.campus-booster. The possible values are: Number (default value). long and full String or The local for representing the date Locale String or Defines the time zone for which one represents the date. Then.

Before being able to use this converter.firstName = firstName. The 2 methods have as parameter the FacesContext instance and the component for which one the conversion is done. UIComponent component.lastName.person}" converter="myConv" /> With the tag <f:converter>.firstName + " " + this. this. public String toString() { if (firstName. it should be declared.net/Booster/Pages/lectureSimpleViewer. UIComponent component. Radio Buttons.. The tag <converter-id> will define the identifier of the converter in JSF pages.id = id. the tags concerned are: selectManyCheckbox selectOneRadio selectOneListBox. it is possible to create your own. Example: <converter> <description>Mon premier convertisseur</description> <converter-id>myConv</converter-id> <converter-class>com. That is made in the file "faces-config. } } } This class simply defines a person who has a unique identifier.length() > 1) { return this. Example: <h:outputText value="#{conv.aspx?lecture=814&PM=True Page 79 of 100 .convert.lastName. public Person(int id. String value). it is enough to refer the identifier of the converter.labosun. } //Getters et setters for all the properties . xml" using the tag <converter>. Example: <h:outputText value="#{conv.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 Custom convertor If the base converters are not enough for you. We will start by seeing what happens without data converter.lastName = lastName. /** * @param value This object is used to create/retrieve an object */ String getAsString(FacesContext context.. private String firstName. For recall. private String lastName. public class PersonConv { /** https://www..person}"> <f:converter converterId="myConv" /> </h:outputText> Convertor for lists At the time of the chapter on Checkbox. package com. Object value). There are 2 manners of using a converter: thanks to the attribute " converter " thanks to the attribute <f:converter>.campus-booster. The 2 methods to be redefined are: /** * @param value This string value is used to create/retrieve an object */ Object getAsObject(FacesContext context. lists and Combobox. we will use the tag selectOneRadio which will make it possible to choose between several instances of the following class "Persson": public class Person { public static int IDS = 0.Converter". Finally the tag <converter-class> represents the class of your converter. We will now define the bean which will define the list of SelectItem.converter. selectManyListBox selectOneMenu In this example. While passing by the attribute "converter". this. } else { return this. String lastName) { this. the attribute "converterId" must refer the identifier of the converter. You only have to implement "javax. we saw that it was necessary to use a converter to store personalized objects.faces.labosun.MyConverter</converter-class> </converter> The tag <description> makes it possible to give a description to the converter. String firstName. a name and a first name. private int id.

String value) { int id = Integer.add(new SelectItem(p.get(i). you will understand later why. "Johnson")). /** * @param value person " id ".size() 1. public class PersonConv implements Converter { .add(new Person(1. "Raymond".person}"> <f:selectItems value="#{personList.aspx?lecture=814&PM=True Page 80 of 100 .getId() == id) { return p. But when the tree of JSF components must be rebuilt. Therefor it is necessary to create a converter which will take care of this translation. But the last instance of people is not taken out of the list. public PersonConv() { allPersons = new ArrayList<SelectItem>(). "Bob"..i++) { Person p = PERSONS_LIST. this. https://www. p.campus-booster. Take a look at the following HTML code : Jo Johnson <input type="radio" value="Jo Johnson" /> Raymond Schmitt <input type="radio" value="Raymond Schmitt" /> Bob LeNain <input type="radio" value="Bob LeNain" /> We can see here that the value of the radio buttons (attribute value in HTML code) uses the method toString () of the class Persson. "Jo".toString())). Here now our JSF page. Indeed.. the JSF Servlet does not know how to reinstantiate the object Persson from this String. PERSONS_LIST... } /** * @param value A " person " object. package com.valueOf(value). for (Person p : PERSONS_LIST) { if (p. p. "LeNain")).net/Booster/Pages/lectureSimpleViewer. the following error occurs: Notice: error message should be displayed in English if your web browser is configurer in English.toString())).add(new SelectItem(p.. } Person p = new Person(3. PERSONS_LIST. for (int i = 0. this. static { PERSONS_LIST.add(new Person(3.. } } return null. the objects of type Person are translated into a String thanks to the method toString (). "LeNain").labosun.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 * This list simulat at data source */ public static final List<Person> PERSONS_LIST = new ArrayList<Person>(). /** * A person currently selected */ private Person person.allPersons. i < PERSONS_LIST. To create the converter. UIComponent component. } //Getters et setters for all the properties . JSF is completely internationalized in almost 10 languages (including Chineese). It contains as many radio buttons as there are people in the list and it posts the currently selected element? <h:form> <h:selectOneRadio id="persRadio1" value="#{personList. "Bob". this is voluntary.. * @return an object related to the id */ public Object getAsObject(FacesContext ctx.person}" /> <br /><br /> <h:commandButton value="Valider" /> </h:form> The result : If you try to validate. */ private List<SelectItem> allPersons. } The constructor creates a list of SelectItem (Al) from our list of people (PERSON_LIST). That means if JSF page is translated into HTML.allPersons}" /> </h:selectOneRadio> <h:message for="persRadio1" /> <br /> Résultat: <h:outputText value="#{personList. "Schmitt")). we are using the "Person" identifier. } /** * SelectItem list which return the content of a select request .add(new Person(2.allPersons.

allPersons}" /> </h:selectOneRadio> Everythings works very well for the first 2 instances.getId(). Object value) { if (value == null || !(value instanceof Person)) { return ""..person}" converter="persConv"> <f:selectItems value="#{personList.getClass()) { return false. we can see: Jo Johnson <input type="radio" value="1" /> Raymond Schmitt <input type="radio" value="2" /> Bob LeNain<input type="radio" value="3" /> The radio button value use identifiers related to the objects.net/Booster/Pages/lectureSimpleViewer. Attention. } Now everything works fine. the checkboxes. In short it is necessary: Create a converter (Implement Converter).xml" Reference the converter in the tag select. but when the 3rd button is selected.labosun.getId(). the radio buttons.aspx?lecture=814&PM=True Page 81 of 100 .. during this one. In our case. The error message specific to the 3rd button occurs because JSF will check if the object returned by the converter belongs well to the list of the items.e.. For example. Define the converter in "faces-config. the lists and the comboboxes. This means that the equality is only based on the equality of the references (==). So this only works for the 2 first instances. I. the order of treatments of the validations is the order of the tag declarations. If there are several validations. } return this. The validation is carried out during the phase "Validation of the user entries".SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 * @return " id " of the person. and then JSF will check if the returned instances belong tothe list "allPersons". (attribute converter) Implement the methods hashCode() and equals() This example is simply adaptable to a tag of type selectMany. } return "" + ((Person) value).. This checking is done using the methods hashCode () and equals (). remember that only the first 2 instances of the list "allPersons" come from list "PERSONS_LIST". That makes it possible to force a validation to be done before all the others. */ public String getAsString(FacesContext ctx. it is those of the class Object which are used. It must seize the country and the city in which it lives.. a person wishes to be recorded on a site. all the elements are not yet up to date (the javabeans are updated only during the "Update model" phase).campus-booster. you can set the attribute "required" to true. To force the user to seize a value. As the class Persson does not redefine the methods hashCode () and equals (). our converter returns instances coming from object "PERSONS_LIST". the following error occurs: If you have a look at the HTML code. The validation of the country can be made immediately to be sure that the validation of the city is considering the country. Validation JSF makes it possible to validate all the data seized by the user. it is enough to implement these 2 methods in the class Person: public boolean equals(Object o) { if (o == null || getClass() != o.PersonConv</converter-class> </converter> It now remains to refer the converter in our tag selectOneRadio: <h:selectOneRadio id="persRadio1" value="#{personList.getId(). So that this works for all the cases. Example: https://www. } } The converter has to be declared: <converter> <converter-id>persConv</converter-id> <converter-class>com. Note: If the component which declares the validation has the attribute "immediate" set to true. the text fields. UIComponent component. The validation is only possible for the components which implement EditableValueHolder. then the validation is treated during the phase "Request parameters application". } public int hashCode() { return this. But.getId() == ((Person) o).

contains("@") == false) { FacesMessage fm = new FacesMessage("Email is not compliant"). The method which manages the validation must have the following prototype: public void validate(javax. All these tags have the attributes "minimum" and "maximum" which define the ranges in which a value must be to be valid.aspx?lecture=814&PM=True Page 82 of 100 . The only method to redefine : public void validate(FacesContext context..faces..FacesMessage". To use this validator.net/Booster/Pages/lectureSimpleViewer. <f:validateLength>. } } } We are now declaring our bean in the file « faces-config. the method must throw a "javax. } if (value != null) { String field = (String) value. a message which is intended for the user.xml ». Object value) throws ValidatorException { if ((context == null) || (component == null)) { throw new NullPointerException(). allows to test if an integer is in a range.e.UIComponent component.validator class --> <validator-class>com. https://www. javax. They are usable thanks to the tags: <f:validateDoubleRange>.methodName }" /> Interface It is necessary to implement the interface « javax. throw new ValidatorException(fm).ValidatorException".faces. public void validate(FacesContext context. Example : <h:inputText> <f:validator validatorId="emailValidator" /> </h:inputText> Example: Email validator To illustrate the operation of a validation. The constructor takes as parameter an object of type "javax. it should be declared in the file "faces-config. We will just check the presence of the character « @ ».EmailValidator</validator-class> </validator> The validator can then be used thanks to the tag <f:validator>.validation.FacesContext context. i. There are 2 manners of making it.Validator ». Custom validator It is possible to create its own validator.labosun. <f:validateLongRange>.. if (field. UIComponent component.faces. <h:inputText id="name"> <h:outputLabel for="name" value="Name:" /> <f:validateLength minimum="3" maximum="10" /> </h:inputText> <%-. Example : <h:form> .context.component.faces. UIComponent component. either by using a method. Object value) { //Event handling } If there is a validation error. </h:form> Here the entire form will not be validated if the value entered for this field text does not have a length ranging between 3 and 10. xml" using the tag <validator>.Display a validation message --%> <h:message for="name" /> .faces. allows to test the length of a string. This message will then be posted thanks to the tag <h:message>. we will create a very basic email validator.faces. allows to test if a number with comma is in a range.campus-booster. The method can then be referred thanks to the attribute " validator ". Generic method Any JavaBean can declare the method. <h:inputText validator="#{nomDuBean.Validator.validator.. Object value). but it must be referred as JavaBean is managed by the container. JSF provides 3 standard validateurs. The validation errors are posted by the tag <h:message>.Validator ".validator.validator identifier --> <validator-id>emailValidator</validator-id> <!-.application. a validator should be used. either by implementing the interface " javax.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <h:inputText required="true" /> To carry out a more precise control on the data. the attribute "validatorId" must refer the identifier of the validator. Example : <validator> <!-.

campus-booster. String message.xml » : <application> <localeconfig> <defaultlocale>en</defaultlocale> </localeconfig> </application> The chapter « 8. <h:form> <h:inputText id="emailMethod" validator="#{beanMail.sun.html. but for recall. If you want to change the default locale.4.3 Example: Change language button » explain how change the locale.doc. and the second is the locale we want to use. String key = "dynamicMessage". String basename = "conf. context.labosun » package.aspx?lecture=814&PM=True Page 83 of 100 .1.SiteMessages" var="msg"/> <f:view> <h:outputText value="#{msg.labosun. you will need to prefix the file by the package name. this code will be used : <f:loadBundle basename="com.sun. The list of available encoding is on the page: « http://java.message}"/> </f:view> In this case.2/docs/guide/intl/encoding.SiteMessages". FacesContext context = FacesContext.html » Example: Change language button https://www.com/docs/books/tutorial/i18n/index. To do this.keyName}" /> Example: We have a properties file called « SiteMessages.checkEmail}"> <h:outputLabel for="emailMethod" value="Email:" /> </h:inputText> <h:message for="emailMethod" /> <br /> <h:commandButton value="Vérifier l'email" /> </h:form> If a text which was entered does not contain an "@".properties » in the « com. if the file is in a package. To use a properties file in a JSF page. mais pour rappel. the locale used will be the locale of the users. it is necessary to use the getBundle method from the RessourceBundle method. the tag <h:message> posts the message "an email must contain an @".. A properties file is a list of keys / values. The attribute « var » will be used in the page to reach the ressources file.EmailValidator</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> </managed-bean> The last thing to do is to write the code of the page and to refer the method of our bean by using the attribute Validator. Advanced concept Internationalization The internationalization of JSF pages is done with properties file.getBundle(basename. Caution.getLocale()). Encoding Normalement la notion d?encodage a déjà été vue dans le cours JSP.getString(key). Dynamic internationalization It is sometimes need to reach a properties file from a JavaBean. it is possible to change the encoding of apages with the following attributes: <%@ page pageEncoding="UTF8" contentType="text/html.net/Booster/Pages/lectureSimpleViewer. } catch (Exception e) { // exception handling } // retrieving a localized message message = bundle. This properties file contains this line : message=hello To use it in a page. il est possible de changer l? encodage des pages grâce à la directive de page : The encoding concept has already been seen. try { ResourceBundle bundle = ResourceBundle.com/j2se/1.labosun. We reach one key defined in the ressources file like this : <h:outputText value="#{variable.getViewRoot(). you need to use this code in the file « faces-config.getCurrentInstance(). See the tutorial of Sun for more informations on properties file here : http://java. the <f:loadBundle> tag is used like this : <f:loadBundle basename="fileName" var="variable" /> The attribute « basename » indicate the name of the properties file who will be used. charset=UTF8" %> By default it is the value « ISO-8859-1 » which is used. The first attribute of this method is the name of the properties file.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <managed-bean> <managed-bean-name>beanMail</managed-bean-name> <managed-beanclass>com.

getCountry().getId(). import java.UIComponent.sun. Here.sun.changeLocale}" /><br /> </h:form> </f:view> </body> </html> This page use properties files. all errors are moved up to the user via a message system. <%@ taglib uri="http://java. we will sight how changed the site language.labosun. Starting with make the Web page.ChangeLocaleRB" var="change" /> <%-.french}" actionListener="#{changeBean.faces. The current locale will be shown and 4 link will perform the language change.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 In this example.currentLocale = newLocale.context. xml »: <faces-config> <managed-bean> <managed-bean-name>changeBean</managed-bean-name> <managed-bean-class>com.aspx?lecture=814&PM=True Page 84 of 100 . for (int i = 0. when an user click on a link.changeLocale}" /><br /> <h:commandLink id="CA" value="#{change. getViewRoot().We load the properties file --%> <f:loadBundle basename="com. } } if (newLocale == null) { newLocale = Locale.com/jsf/html" prefix="h" %> <html> <body> <f:view> <%-. import javax.deutsch}" actionListener="#{changeBean. import javax.properties »: currentLocale=The current Locale is french=French english=English canadian=Canadian deutsch=Deutsch We need now to write the JavaBean who will perform the language change : package com.changeLocale}" /> <br /> <h:form> <%-.setLocale(newLocale).net/Booster/Pages/lectureSimpleViewer.Locale.util.length.i18n.currentLocale} #{changeBean. public Locale getCurrentLocale() { return currentLocale. this. newLocale == null && i < locales.Link to change language --%> <h:commandLink id="FR" value="#{change.getViewRoot().english}" actionListener="#{changeBean. * @param newLocale La nouvelle Locale */ public void setCurrentLocale(Locale newLocale) { FacesContext.getDefault().changeLocale}" /><br /> <h:commandLink id="DE" value="#{change. } public void changeLocale(ActionEvent ae) { String id = ae.i18n.15 Error message ».faces.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.getAvailableLocales().getComponent(). } } Then we must declare this Javabean in the file: « faces-config. i++) { if(locales[i]. it is https://www. public class ChangeBean { /** * Contains the current locale */ private Locale currentLocale = FacesContext.component.getLocale(). } /** * Change the locale of the current view.i18n.ActionEvent.getCurrentInstance().getCurrentInstance().canadian}" actionListener="#{changeBean. } setCurrentLocale(newLocale).changeLocale}" /><br /> <h:commandLink id="US" value="#{change.labosun. Locale newLocale = null. import javax.equals(id)) { newLocale = locales[i]. // we get all available locale Locale[] locales = Locale.event.ChangeBean</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> </managed-bean> </faces-config> Messages management As seen at the chapter « 5.Print the current locale --%> <h:outputText value="#{change.campus-booster. Here is the contents of 2 properties files ( english and french ) : File « ChangeLocaleRB_fr.FacesContext.properties » : currentLocale=La Locale actuelle est french=Français english=Anglais canadian=Canadien deutsch=Allemand File « ChangeLocaleRB_en.faces.labosun.

SEVERITY_WARN. import javax. "message from MessageBean and specif context. It is impossible to redefine these messages by creating a new properties file with the same keys. Messages are saved in the application with the « addMessage(String clientId. « validatorMessage » : define the message used when the entered value is not validated by the component.application.) to send a message who will be printed in a page. In JSF 1.UIInput. To have a valid identifier.getCurrentInstance().SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION possible since any type of JavaBean (actionListener.MessageBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> Customize messages The default errors messages not always correspond to your application. « requiredMessage » : define the message when no value is entered.SEVERITY_INFO. We will then define it to replace the default file.faces. It is it which make the two messages « f » and « f2 ». the default errors messages are in the « Message_fr. import javax.REQUIRED= Validation error : You must enter a value. //Retrieve component id String nameId = nameInput.properties » file.message. all components who inherit of UIInput allows personalization of the message very easily with 3 attributes : « converterMessage » : define the message when the value of the component can't be convert.application. f).ActionEvent. a detail of the error ( properties « detail » ). public UIInput getNameInput() { return nameInput. javax.faces. A JSF message is represent by the « javax. we will copy the keys/values of the original « Message_fr. "Specific message summmary".sun. we need to use the attribute « binding ». <%@ taglib uri="http://java. then it is a global message.addMessage(null.nameInput}"> <h:outputLabel for="name" value="Name:" /> </h:inputText> <h:message for="name" styleClass="errorTable" errorClass="error" infoClass="info" fatalClass="fatal" warnClass="warn" /> <h:commandButton value="Valider" actionListener="#{messageBean. FacesMessage message) » method of the « FacesContext » class.FacesMessage » class.xml » file. For example. https://www.css" rel="stylesheet" type="text/css" /> </head> <body> <f:view> <h:messages globalOnly="true" showDetail="false" showSummary="true" styleClass="errorTable" errorClass="error" infoClass="info" fatalClass="fatal" warnClass="warn" /> <h:form> <h:inputText id="name" size="10" binding="#{messageBean.properties » file.faces.event.nameInput = nameInput.faces.component. who is in the « java. For all others messages and for JSF 1. public class MessageBean { private UIInput nameInput. if its null.UIInput. and the severity of the error ( properties « severity » ). The second message is specific to the component « nameInput ». the easiest way is to get directly the component identifier with the « UIComponent. "Global message summary".check}"/> <br /> <h3>List</h3> <h:messages showDetail="true" showSummary="true" styleClass="errorTable" errorClass="error" infoClass="info" fatalClass="fatal" warnClass="warn" /> <h3>Table</h3> <h:messages showDetail="true" showSummary="false" layout="table" styleClass="errorTable" errorClass="error" infoClass="info" fatalClass="fatal" warnClass="warn" /> </h:form> </f:view> </body> </html> Last stage. validation. "message from MessageBean").1.properties » properties file. } } The attribute « nameInput » will be linked with a component for recovered its identifier.jar » jar file..faces. Fortunately it is possible to change these.addMessage(nameId.component..com/jsf/core" prefix="f" %> <%@ taglib uri="http://java. The attribute « cliendId » allows to link the message to acomponent. f2).net/Booster/Pages/lectureSimpleViewer.campus-booster. This new file can be anywhere in your application. Each message have a summray of the error ( properties « summary » ).labosun. Let us see now an example of making messages from a Javabean: 17/10/09 18:17 package com. we need to save the JavaBean in the « faces-config.labosun.aspx?lecture=814&PM=True Page 85 of 100 .FacesMessage.2. of « jsfimpl. import javax.faces. in which. To link the attribute « nameInput » with the component of text type in the JSF page. FacesMessage f2 = new FacesMessage(FacesMessage.getId() » method. <managed-bean> <managed-bean-name>messageBean</managed-bean-name> <managed-bean-class>com.getClientId(context). The first message is global since one does not use an identifier at the « context » addition. import javax. } public void check(ActionEvent ae) { FacesContext context = FacesContext. .sun.FacesContext. we will create the « MyDefaultMessages_fr. context. FacesMessage f = new FacesMessage(FacesMessage.faces » package.message. } public void setNameInput(UIInput nameInput) { this. The check method is used as ActionListenener.context. converter.com/jsf/html" prefix="h" %> <html> <head> <link href="style.

EJB injection EJB injection allows getting an instance of Local or Remote interface.UIInput. Store store = (Store)ctx. In these messages.1 and 1. Example : @Resource private SessionContext ctx. Persistence unit injection It is possible to get an instance of one EntityManager.REQUIRED= Personalized message : This field is required. but settles to easy the writing of code by letting code template creation.Service ». but it is obvious there are numerous problems when both are mixed. Now. Facelets works with the JSF implementations 1. we will define a variable who will be create by the container. @WebServiceRef public StockQuoteService stockQuoteService. Like in EJB3.MAXIMUM= Personalized message : The value ''{0}'' is superior to the maximum authorized for this field. syntax "{0}" allows insert of parameters. Example : @EJB private Store store. we will put these messages: javax. Example: @PersistenceContext(unitName="InventoryManagement") EntityManager em. ''{0}'' You will notice that all special characters are unicode. It is used with the annotation « @EJB ». injection is done with the annotation « @PersistanceContext ». For this. the variable of "ctx" will be initialized.net/Booster/Pages/lectureSimpleViewer. The Facelets goal is to create a set of tags that are well matched with JSF and also give a new way to write JSF code. Facelets Introduction JSF was designed to work with JSP.LengthValidator. It does not add new internal mechanisms to JSF. Resource injection Ressources injection allow by example to get an instance of the JNDI current context.campus-booster. It is defined in the JSF configuration file: <faces-config> <application> <locale-config> <default-locale>fr</default-locale> </locale-config> <message-bundle>MyDefaultMessages</message-bundle> </application> </faces-config> JSF Integration in JEE application The new JEE 5 specification bring annotation who can be used for interact with the lower layer of your application. The « unitName » field allows informing the unit of persistence name to be used. javax.2 of Sun and Apache MyFaces.faces. this field must be defined in the « persistence.faces.validator. We need a JEE 5 valid server to use these annotations. Example: @Resource private SessionContext ctx.LengthValidator. This uses the MessageFormat class.xml. with the injection principle. With the deployment of application. This file is used in place of the default file.validator. the unified language EL should be used in two different ways according to the JSP or JSF context (syntax ${} and #{}).component. To be valid. It is used with the annotation « @Ressource » .xml » file. Facelets also provides the following enhancements: Possibility to create pages in several files More precise display of errors Quicker creation of custom tags https://www.lookup("Store").ws. WebService injection It is possible to get a WebServices who inherit of « javax.faces. To only quote one. Injection is used with the annotation « @WebServiceRef ».SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 javax.MAXIMUM= Validation error : the value is superior to the maximum authorized : .aspx?lecture=814&PM=True Page 86 of 100 . Is is also possible to use ressources injection to get an instance on JNDI current context and to seek then the EJB.

see the chapter "JSFC") To understand what brings Facelets. Other phases stay unchanged.jar" and "el-ri. <web-app> <!-. you should download the last implementation of Facelets at this address: https://facelets.DEVELOPMENT</param-name> <param-value>true</param-value> </context-param> </web-app> https://www. Every libraries (jar) needed by the project. Configuration We are now going to see modifications to do to the files "faces-config. In the case where you do not use a JEE 5 server.jar" and "el-ri. The structure of a War file stays the same as for JSF. this means it is possible to change some components in the JSF internal.faces.jar" that are placed in the directory "lib". we have to come back to the life cycle of a Web page. This extension is not mandatory. Here it is: Table 1. we will see how to install and configure Facelets to use it in a project. but the syntax of Facelets follow the xHTML format.Extension .faces.DEFAULT_SUFFIX</param-name> <param-value>.jar". among others). You then have to uncompress the archive and get the file "jsf-facelets. ie. we will define the extension ". Facelets deals with replacing view components. Configuration In this chapter. JSF was designed to be modular.dev.campus-booster.xhtml". Configuration file. It is then more logical to use that extension. we shall use the context parameter "javax. WEB-INF/classes WEB-INF/lib WEB-INF/facesconfig.xhtml" files should be placed at the root. The only difference is the extension of Web pages. all the syntax of the files can be changed and entirely retought by Facelets. Here is a reminder of the life cycle.jar". Contains all the Java classes (the JavaBeans.11".net/Booster/Pages/lectureSimpleViewer.java. Project Structure Facelets respects the same structure as a standard JSF application.xml WEB-INF/web.net/ This lesson is based on version "1.DEFAULT_SUFFIX". you should take the files "el-api.xhtml for JSF pages --> <context-param> <param-name>javax.xml" pour to be able to use Facelets. Useful for development --> <context-param> <param-name>facelets. Installation First of all. First of all.xhtml All ". the phases "View Restoration" et "Reply Rendering". As seen in the chapter "Context parameters ".xhtml</param-value> </context-param> <!--Specific parameter to Facelets.xml" and "web. Those are Facelets pages.xhtml" as pages extension.jar".SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Simple configuration Let to use JSF tags as standard HTML ones (attribute jsfc. The Facelet library: "jsf-facelets. it is ".1.xml *. Eventually: "elapi. Yellow parts are managed by Facelets: 17/10/09 18:17 Thanks to the control of those two phases.aspx?lecture=814&PM=True Page 87 of 100 .

There is no tag <f:view>.w3.sun. Here is a first example of a Facelets page: Hello.com/jsf/facelets" allows to use all the Facelets tags.org/TR/xhtml1/DTD/xhtml1-transitional.jsf". Whereas the two next ones allow to use the JSF libraries. This allows to call a page by replacing the extension ". For instance.0 Transitional//EN" "http://www.sun.w3.sun.webapp.sun.f}" displays directly the value of the parameter "f".org/1999/xhtml" xmlns:ui="http://java.jsf" is the name of the page.xhtml : <?xml version="1. Facelets will do the interpretation as a tag <h:form>.jsf" is used. However.sun. We must use the URL: http://localhost:8080/JSFCoursFacelets/Hello. Here.sun. JSFC One of the problems that arise with the JSF tags is that editors do not all know how to render a page in a graphics way. the suffit ".com/jsf/html" xmlns:f="http://java.com/jsf/facelets" xmlns:h="http://java. the view management (creation of the JSF component tree. charset=UTF8"/> <title>Form with JSFC</title> </head> <body> <form jsfc="h:form"> <input id="name" type="text" jsfc="h:inputText" value="#{bean. If we execure this page by setting the parameter "f=Facelets" in the URL. we declare all the libraries like namespaces in the <html> tag.dtd"> <html xmlns="http://www.xhtml" by ". Let us see an example: <?xml version="1.w3.FacesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.w3.0 Transitional//EN" "http://www.com/jsf/facelets" xmlns:h="http://java.sun. the code "#{param. The expression "xmlns:ui=http://java.org/1999/xhtml" xmlns:ui="http://java.name}" required="true"> <label for="name">Name:</label> </input> <h:message for="name" /> <br /> <button type="submit" jsfc="h:commandButton" value="Validate" /> </form> </body> </html> Let us take the tag <form jsfc="h:form">.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.campus-booster. but from a code editor perspective it is only a simple <form> tag.com/jsf/html" xmlns:f="http://java.aspx?lecture=814&PM=True Page 88 of 100 .jsf</url-pattern> </servlet-mapping> </webapp> We now need the JSF Servlet forward calls to Facelets for the view management. This is done in the file "facesconfig.com/jsf/core"> <body> <h:outputText value="Hello" /> #{param. To remind you. it is possible to use an EL expression directly in the HTML code.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 In the following examples. most of code editors know how to display an HTML page. One of the possibilities offered by Facelets is to display the result of a page as HTML and without it being executed on the server.org/TR/xhtml1/DTD/xhtml1-transitional.faces.facelets.xml": <faces-config> <application> <view-handler> com. The attribute "jsfc" serves to define the real type of the tag.FaceletViewHandler</view-handler> </application> </faces-config> Thanks to this configuration.0" encoding="UTF8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. The advantage https://www.net/Booster/Pages/lectureSimpleViewer.f} </body> </html> The first different in relation to a classical JSF page is that the taglibs declaration is different.dtd"> <html xmlns="http://www. rendering of the reply) will be managed by Facelets and not by the JSF implementation anymore. here is how to declare it: <web-app> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.sun. This is done thanks to the attribute "jsfc".jsf?f=Facelets . Finally. Core Concepts Page Structure The structure of the facelet pages respect the format xHTML.0" encoding="UTF8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. we get the text: Hello Facelets This is an example assuming "JSFCoursFacelets" if the context of the project and "Hello.

the menu.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html. we must write the template page.. It is more practical to only declare them once and that they get integrated directly to other pages.xhtml" /> </ui:insert> </div> https://www.org/1999/xhtml" xmlns:ui="http://java. A page that uses a template is named a "calling page". In this example. left: 0%. Facelets allow to do that thanks to its template system.org/1999/xhtml" xmlns:ui="http://java.sun. View Templating Now that we understand the basic syntax of Facelets and the concept of templates. a menu.0 Transitional//EN" "http://www. MainTemplate.. Template2.sun.campus-booster. By default.org/TR/xhtml1/DTD/xhtml1-transitional. charset=UTF8"/> <title> <ui:insert name="Title">Default Title</ui:insert> </title> </head> <body> <div style="background: cornflowerblue.0" encoding="UTF8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. we will see how this can be done in practice.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html. without forgetting that we always still can add EL expressions directly in the HTML code. charset=UTF8"/> <title></title> </head> <body> <ui:composition template="Template1. One of the most occurring problems during the creation of a Web site is that every page should redefine all the page layout of the site. charset=UTF8"/> <title></title> </head> <body> </body> </html> 17/10/09 18:17 Here. a body and a footer. the chapter "Facelets" will present other tags to use templates. all the tags of the pages that use the template are ignored.com/jsf/html" xmlns:f="http://java.com/jsf/facelets" xmlns:h="http://java.org/TR/xhtml1/DTD/xhtml1-transitional. we must use the tag <ui:composition>. this is the equivalent of a tag. This is the case for the attribute "required" for the tag <input>.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION here is to be able to work with standard HTML tags and let let editors graphically display them in a simple editor. Let us see how it works with a first example First of all. This lesson part is only concentrating on the basic declaration of a template. To only use a portion of code as a template.0 Transitional//EN" "http://www.dtd"> <html xmlns="http://www.w3. we will create a site that contains a header. Template A template is a Facelets code that can be reused.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. Templates will be applied at wish in the site.dtd"> <html xmlns="http://www.xhtml" will be displayed on the client. Ie.sun. position: absolute.sun.com/jsf/html" xmlns:f="http://java. the entire page is considered as a template.net/Booster/Pages/lectureSimpleViewer. For the JSF tags that do not have HTML equivalents like the tag <h:message> for instance. redefine the title.w3.w3.xhtml"> </ui:composition> </body> </html> The result of this example will be that the content of the page "template1.sun.org/1999/xhtml" xmlns:ui="http://java. we should include it directly in the code. except that a template is written in a very simple manner and is more easily modular. bottom: 95%. Template1.sun.sun.w3. Every Facelets file can serve as a template.com/jsf/facelets" xmlns:h="http://java. In our example.w3. This behavior is specific to the tag <ui:composition>. the footer. this is all of a page that defines a template. Attributes specifics to a JSF tag should be added to the HTML tag. Those elements are often the sames for every pages of the site. We will later see that there are several manners to use a template.sun. right:0%.sun. but it will work correctly for Facelets.w3. This example is quite limited because it is equivalent to the inclusion of a page.com/jsf/facelets" xmlns:h="http://java. top: 0%"> <ui:insert name="Header"> <ui:include src="Header.aspx?lecture=814&PM=True Page 89 of 100 .com/jsf/html" xmlns:f="http://java.dtd"> <html xmlns="http://www.0 Transitional//EN" "http://www. We then get a mix of HTML and JSF tags.org/TR/xhtml1/DTD/xhtml1-transitional.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.xhtml: <?xml version="1. We will see in the next chapter how to create and use modifiable templates. it will describe the structure of the site and the elements that other pages can modify. An HTML editor will certainly indicate that the attribute does not exist for that tag.

sun.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. It is not mandatory to https://www. The tag <ui:composition> is used to define a bloc of code that can be reused in other pages.sun.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html. it does not serve to declare a template (like in HeaderTemplate. For the tag: <ui:insert name="Header"> <ui:include src="Header.0 Transitional//EN" "http://www.xhtml" /> </ui:insert> It does not define directly the default header. The text "Default Footer" is the text displayed by default. left: 10%. In fact. </ui:composition> It uses the attribute "template". we begin by taking all the code of the page of the attribute "template".xhtml"> . <ui:insert> and <ui:include>. top: 95%"> <ui:insert name="Footer"> Default Footer </ui:insert> </div> </body> </html> There are two tags specific to Facelets in this template page. The order of the tags "define" does not matter. we do not modify the parts "Title". "Footer" and "Body".w3. we replace the modifiable parts (bodies of the tags <ui:insert>) by the content of the tags <ui:define>.A tag define must match a <ui:insert> tag in the template --> <ui:define name="Title">Main Page</ui:define> <ui:define name="Footer">Footer</ui:define> <ui:define name="Body">Redefined body of the page</ui:define> </ui:composition> </body> </html> The tag " <ui:composition>": <ui:composition template="MainTemplate.5 Include ".org/TR/xhtml1/DTD/xhtml1-transitional.xhtml"> <!-.sun. Our template is now read. Here.campus-booster.sun. left: 0%.w3. HeaderTemplate.com/jsf/facelets" xmlns:h="http://java.w3.com/jsf/facelets" xmlns:h="http://java. The import is done with the tag <ui:include>.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html. right: 0%. We will see the inclusion principle in detail in the chapter " 1. charset=UTF8"/> <title></title> </head> <body> <ui:composition> Default Header </ui:composition> </body> </html> This page contains the default code for the header. right: 0%. "MainTemplate. top: 5%.aspx?lecture=814&PM=True Page 90 of 100 . left: 0%.sun.xhtml".xhtml) but to precise that we want to use an existing bloc of code. In this case. bottom: 5%.com/jsf/html" xmlns:f="http://java. right: 90%.. Each tag use a name to uniquely identify the part In the case of the tag: <ui:insert name="Footer"> Default Footer </ui:insert> It defines all the footer part that is modifiable. This behavior is due to the tag <ui:include> that ignores the rest of the page as soon as it finds a tag <ui:composition>.net/Booster/Pages/lectureSimpleViewer.dtd"> <html xmlns="http://www. PageMain.0 Transitional//EN" "http://www. charset=UTF8"/> <title>Main Page</title> </head> <body> <ui:composition template="MainTemplate.4.org/TR/xhtml1/DTD/xhtml1-transitional. position: absolute. In our case.bottom: 0%.sun.. bottom: 5%.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <div style="background: darksalmon.dtd"> <html xmlns="http://www."> <ui:insert name="Body"> Default Body </ui:insert> </div> <div style="background: lawngreen.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. when another page that use the template to not modify the footer. top: 5%.org/1999/xhtml" xmlns:ui="http://java."> <ui:insert name="Menu"> <a href="">Default Menu 1</a><br /> <a href="">Default Menu 2</a><br /> <a href="">Default Menu 3</a><br /> </ui:insert> </div> <div style="position: absolute.com/jsf/html" xmlns:f="http://java. First. we can create the page that will use the template. but import a file that contains the default text.org/1999/xhtml" xmlns:ui="http://java. Then. that means that it will never appear in an HTML page received by the client.w3. position: absolute. all the code that is arround the tag <ui:composition> is ignored. the tags <ui:insert> allow to define the modifiable parts of the template.

charset=UTF8"/> <title>Main Page</title> </head> <body> <!-.Valid define tag --> <ui:define name="Footer">Footer</ui:define> <!-. Facelets Tags Composition The tag <ui:composition> allows: Either to define a template zone.Ignored tag --> <ui:define name="Menu">Menu not took into account</ui:define> <!-.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html. the following code will generate the same HTML page.w3.Ignored tag --> <ui:define name="Title">Title not took into account</ui:define> <!-. Define a Template Take the first case to define a template zone.xhtml"> <ui:define name="Menu">Menu</ui:define> <ui:define name="Body">The body.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION redefine all parts. Ie.This composition tag is completely ignored --> <ui:composition template="MainTemplate.Valid define tag --> <ui:define name="Title">Main Page</ui:define> This text is ignored <!-.net/Booster/Pages/lectureSimpleViewer.Valid define tag --> <ui:define name="Body">Redefined body of the main page</ui:define> </ui:composition> <!-. all the code that is not inside valid <ui:define> tags are also ignored.campus-booster. to create a skeleton of page that you can reuse as you wish. Moreover. https://www.sun.0 Transitional//EN" "http://www. It is possible.Only one composition tag is valid --> <ui:composition template="MainTemplate. All grayed parts are not included in the HTML page that the client receives.sun.</ui:define> </ui:composition> </body> </html> The working of the different tas will be reviewed in detail in the rest of the lesson.w3. again. this page is available at the address: http://localhost:18080/JSFCoursFacelets/PageMain.aspx?lecture=814&PM=True Page 91 of 100 .xhtml"> <!-. from this exemple.com/jsf/facelets" xmlns:h="http://java.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.com/jsf/html" xmlns:f="http://java. </ui:composition> It is possible to use <ui:insert> tags to define what zones of the template are modifiables.sun.org/1999/xhtml" xmlns:ui="http://java. every tags <ui:define> that is outside of the dirst <ui:composition> tag are ignored. If "JSFCoursFacelets" is the context of the project.xhtml". <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. Or to use a template by eventually adding modifications (using the attribute "template").jsf The graphical result is: 17/10/09 18:17 Be Careful: In the last page "PageMain. Example: <ui:composition> Reusable part.

com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.sun. the code that is arround the tag <composition> in a calling page is not included in the final reply.org/TR/xhtml1/DTD/xhtml1-transitional. charset=UTF8"/> <title></title> </head> <body> <ui:composition template="TemplateWithComposition.com/jsf/facelets" xmlns:h="http://java. See the chapter " 1. all the page is took into account. Example: <ui:insert name="Partie1"> Modifiable part. It defines a portion of code that can be replaced.w3."> Header </div> <div style=". charset=UTF8"/> <title></title> </head> <body> <ui:composition> <div style=". In every cases. The replacing is then done by the tag <ui:define> that have an attribute "name" too."> Redefined body of the main page."> <ui:insert name="Header">Header</ui:insert> </div> <div style=". </div> Here.sun.org/TR/xhtml1/DTD/xhtml1-transitional.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Template Usage 17/10/09 18:17 A template can be used with the tag <ui:composition>.w3. the attribute "template" must define the URL to the files of the template to use. Else. </ui:insert> It is also possible to use the tag without specifying a name.com/jsf/html" xmlns:f="http://java.org/1999/xhtml" xmlns:ui="http://java..dtd"> <html xmlns="http://www.sun.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.campus-booster.w3.3 View Templating " for an example of use where only the calling page use the tag <ui:composition>.com/jsf/facelets" xmlns:h="http://java.</ui:define> </ui:composition> </body> </html> The result will be: <div style=".net/Booster/Pages/lectureSimpleViewer. Insert The tag <ui:insert> can be used in templates.0 Transitional//EN" "http://www.dtd"> <html xmlns="http://www.xhtml: Start of paragraph <ui:insert /> End of paragraph Page.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1..org/1999/xhtml" xmlns:ui="http://java.w3.. There only need to match both to do a replacement. In this case. Example without name: ParagraphTemplate.com/jsf/html" xmlns:f="http://java.. We will see here a second example where the template page and the calling page both use the tag <ui:composition>..sun.sun.aspx?lecture=814&PM=True Page 92 of 100 .xhtml"> Middle of paragraph </ui:composition> https://www.</ui:insert> </div> </ui:composition> </body> </html> UseTemplateWithComposition. Example TemplateWithComposition..sun. The usage of a template follow those rules: If the template file contains one or several <composition> tags then only the body of the first tag is took into account..0 Transitional//EN" "http://www. we see well that everything that is around the tags <ui:composition> is ignored.xhtml: <ui:composition template="Paragraph.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.. In this case. The attribute "name" let you identify that portion."> <ui:insert name="Body">Default body. all the body of the tags that uses the template will be included.xhtml"> <ui:define name="Header">header</ui:define> <ui:define name="Body">Redefined body of the main page.

We have the same page of template as in the chapter "Example".SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION The generated page will be: Start of paragraph Middle of paragraph End of paragraph Define 17/10/09 18:17 The tag <ui:define> allow to replace the content of a tag <ui:insert>.sun.sun.xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/1999/xhtml" xmlns:ui="http://java.com/jsf/html" xmlns:f="http://java. https://www.0 Transitional//EN" "http://www..dtd"> <html xmlns="http://www. charset=UTF8"/> <title></title> </head> <body> <ui:composition> <div style=". It has the mandatory attribute "name" that must match a name of a <ui:insert> tag.. Decoration The tag <ui:decoration> allow to use a template.sun. It works like the tag <ui:composition> except that all the code of the calling page is included in the reply.org/1999/xhtml" xmlns:ui="http://java.com/jsf/facelets" xmlns:h="http://java.net/Booster/Pages/lectureSimpleViewer. The name of the page can be wrote directly ou it can be an EL expression.sun. This mechanism is interesting because one page can still define the tag <html> with all the namespaces.sun.sun."> Header </div> <div style="..w3.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.com/jsf/html" xmlns:f="http://java. Else. TemplateWithComposition.w3. charset=UTF8"/> <title>Page principale</title> </head> <body> <ui:decorate template="TemplateWithComposition.w3.w3.dtd"> <html xmlns="http://www.aspx?lecture=814&PM=True Page 93 of 100 .org/TR/xhtml1/DTD/xhtml1-transitional."> <ui:insert name="Body">Default body</ui:insert> </div> </ui:composition> </body> </html> UseTemplateWithDecoration. charset=UTF8"/> <title>Page principale</title> </head> <body> <div style=". It have the mandatory attribute "src" that designate the page to include.org/TR/xhtml1/DTD/xhtml1-transitional.0 Transitional//EN" "http://www.org/1999/xhtml" xmlns:ui="http://java..com/jsf/facelets" xmlns:h="http://java.campus-booster..xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1..sun.sun. that allow to edit it in an editor.xhtml" /> The inclusion follows those rules: If the file to include contains one or several tags <composition> then only the content of the first tag is took into account. Example that allow to include the page "Footer.xhtml": <ui:include src="Footer.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.xhtml"> <ui:define name="Header">Header</ui:define> <ui:define name="Body">Redefined body of the main page</ui:define> </ui:decorate> </body> </html> The result will be: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/TR/xhtml1/DTD/xhtml1-transitional.0 Transitional//EN" "http://www.. all the page is took into account.w3..com/jsf/html" xmlns:f="http://java."> <ui:insert name="Header">Header</ui:insert> </div> <div style="."> Redefined body of the main page </div> </body> </html> Include The tag <ui:include> allow to include a Facelet page.sun.dtd"> <html xmlns="http://www.com/jsf/facelets" xmlns:h="http://java.w3.com/jsf/core"> <head> <meta http-equiv="Content-Type" content="text/html.

<c:if> Attribute Mandatory test var Yes No Description Expression to evaluate. Contains the current element that we are browsing. Fragment The tag <ui:fragment> is identical to <ui:component> in its working. But this solution has the advantage to not have to comment every single line of code. This is like a comment on a whole bloc (like /* and */). To use it. like the tag <ui:decorate>. Index to which to end the iteration. Point to an object that contains the following properties: boolean first boolean last varStatus int begin int end int index int step Table 4. all the part inside <ui:remove> is not took into account. the tags of the calling page will be included in the final reply. JSTL and Fonctions Tags Facelets proposes an implementation of JSTL Core taglibs and of functions.aspx?lecture=814&PM=True Page 94 of 100 . It has those two mandatory attributes: name value Remove The tag <ui:remove> allow to not take into account all the code that is in its body. The value to add to the index at every iteration. the Map ou the table to browse. else it is ignored. Example: <body> <h:outputText value="affiché" /> <ui:remove> <h:outputText value="Not displayed" /> <form> <%-.com/jstl/core"" Table 2.<input type="text" /> --> <button type="submit" /> </form> </ui:remove> <h:outputText value="Displayed" /> </body> Here. but.campus-booster.net/Booster/Pages/lectureSimpleViewer. we should use the attribute "bindings". Index from which to begin the iteration. Example: <c:if test="#{user.sun. we should declare the following namespace: "xmlns:c="http://java. If the expression is true then the body of the tag is took into account. Variable that must contains the result of the test of the expression. <c:forEach> Attribute items var begin end step Description An expression that points to the Collection. JSTL Core To use the tags JSTL Core.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION Param 17/10/09 18:17 The tag <ui:param> allow to pass parameters to a Facelets bloc of code. <c:set> Attribute Description https://www. It can be used inside the tags <ui:define> and <ui:include>. An expression null is false. except that all the body of the tag is included in a JSF component that we can use. Component The tag <ui:component> is identical to <ui:composition>.roles['admin']}"> </c:if> Table 3.<h:outputText value="Not displayed again" /> --%> <!-.

campus-booster. Facelets Solution Thanks to its template system.org/TR/xhtml1/DTD/xhtml1-transitional.sun.sun.aspx?lecture=814&PM=True Page 95 of 100 .sun. This expression will be reused at every time the variable will be used. the name is a GUI link allowing to sort it --> <c:if test="#{!empty sortMethod}"> <h:commandLink action="#{bean[sortMethod]}"> <h:outputText value="#{columnName}" /> </h:commandLink> </c:if> <!-.0//EN" "facelet-taglib_1_0.xml: <context-param> <param-name>facelets. This tag will generate all the code for different copies.Else.3 View Templating ". there is no copy of this value in the variable designated by the attribute "var".If this column is sortable.com/jstl/core" xmlns:fn="http://java. we must add it in a declaration file.caseValue:Value of the case --> <ui:composition> <h:column> <f:facet name="header"> <h:panelGroup> <!-.taglib. as we have seen in the chapter " 1. For Facelets to load the file.com/jsf/core" xmlns:c="http://java. The file must have the extension ".LIBRARIES</param-name> <param-value>/WEB-INF/facelets/tags/arcmind.com/jsp/jstl/functions"".xhtml: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.xml: <?xml version="1. The only thing that we will have to provide is the list of attributes that can be changed between several copies of the code. labo-sun.0"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems. The expression wich will determinate the value of the variable.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION var value The variable that will contains the value of the attribute "value".com/jsf</namespace> <tag> <tag-name>case</tag-name> <source>CaseComponent.columnName:Name of the column . charset=UTF8"/> <title></title> </head> <body> <!-.dtd"> <html xmlns="http://www.Parameters: .com/jsp/jstl/functions"> <head> <meta http-equiv="Content-Type" content="text/html.xhtml</source> </tag> </facelettaglib> This declaration will allow to use our template with a tag of this kind: <case columnName="" sortMethod="" caseValue="" bean="" /> The attributes of the tag are determined from the variables that are used in the template page. Ie.sun.taglib.w3. CaseComponent.xml". Facelets allow to create a tag that we will use as a component.labo-sun.sun.sortMethod:Name of the method in the bean to sort the column . there are numerous cases where we are obliged to repeat code that is looking pretty the same. we must add the following declaration in the file web.dtd"> <facelet-taglib> <namespace>http://www.xml</param-value> </context-param> Declaration: https://www. This is the case for presentation code.com/jsf/html" xmlns:f="http://java.org/1999/xhtml" xmlns:ui="http://java. we only display the name --> <c:if test="#{empty sortMethod}"> <h:outputText value="#{columnName}" /> </c:if> </h:panelGroup> </f:facet> <h:outputText value="#{caseValue}" /> </h:column> </ui:composition> </body> </html> TagFile To use this component template with to a tag.0 Transitional//EN" "http://www. 17/10/09 18:17 Functions To use the functions.bean:Bean that contains the sort method .net/Booster/Pages/lectureSimpleViewer. but the problems can also arise for personal components. Inc. Components Templating Problem with JSF Despite the simplicity of JSF.taglib.//DTD Facelet Taglib 1.com/jsf/facelets" xmlns:h="http://java. we should declare the following namespace: "xmlns:fn="http://java.sun.w3.

The paths are relative to the root of the applciation.compareTo(o2. A library is loaded only when the page that use it should be compiled.jsf. persons. } public void sortByLastName() { Collections.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <managed-bean> <managed-bean-name>beanTable</managed-bean-name> <managed-bean-class>com.sun.DECORATORS https://www.w3.facelets.w3. our tag is ready to be used.BUFFER_SIZE If true.com/jsf"> <head> <meta http-equiv="Content-Type" content="text/html.getFirstName().tag.add(new Person("Bob". public BeanTable() { persons = new ArrayList<Person>().TagDecorator" with a default constructor. } //Getter et setter public void sortByFirstName() { Collections."à of the type "com. Parameters Description List of paths to libraries of Facelets tags separated by ".org/TR/xhtml1/DTD/xhtml1-transitional.html.0 Transitional//EN" "http://www.com/jsf/facelets" xmlns:h="http://java. a too small buffer size will no allow to display a page in its entirety. persons. By default.persons}" var="person" border="1" rules="all"> <m:case columnName="Last name" sortMethod="sortByLastName" caseValue="#{person. "Smith")). private static Comparator<Person> personFirstNameComparator = new Comparator<Person>() { public int compare(Person o1. The declaration is done with namespaces like that: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.firstName}" bean="#{beanTable}" /> </h:dataTable> </h:form> </body> </html> Here is the final result: Table 5.facelets. /WEB-INF/facelets/car.DEVELOPMENT facelets. The default value is false.add(new Person("Raymond".LIBRARIES Example: /WEB-INF/facelets/my.sun.". } } That's all.taglib.getLastName(). facelets. Person o2) { return o1.sort(getPersons().sun. A list of classes (separated with ". private static Comparator<Person> personLastNameComparator = new Comparator<Person>() { public int compare(Person o1.tag.xml.BeanTable</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> public class BeanTable { private List<Person> persons. the value is 1. personLastNameComparator).sun.add(new Person("Thomas". Sort by Last Name Sort by First Name Parameters Table 6. } }. "Gnoliac")). then debugging informations will be displayed on the Web page when there is an error. Be careful.sort(getPersons(). Example: com.getLastName()). persons. charset=UTF8"/> <title>Test column template</title> </head> <body> <h:form> <h:dataTable value="#{beanTable.aspx?lecture=814&PM=True Page 96 of 100 .labo-sun.sun.taglib.HtmlDecorator facelets. personFirstNameComparator).org/1999/xhtml" xmlns:ui="http://java.labosun. } }. it allows to not facelets.com/jsf/core" xmlns:m="http://www.com/jsf/html" xmlns:f="http://java. The size of the buffer used by the ResponseWriter.facelets.lastName}" bean="#{beanTable}" /> <m:case columnName="First name" sortMethod="sortByFirstName" caseValue="#{person.campus-booster. Those decorators will be loaded during the first query will get to the view "FaceletViewHandler".getFirstName()).xml.dtd"> <html xmlns="http://www.net/Booster/Pages/lectureSimpleViewer.compareTo(o2. Person o2) { return o1. "Anderson")).

sun.*. This page will ask a nane to the user.1 : http://java.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION set any size limit.apache. Create a new class named Movie.html Facelets homepage: https://facelets.com/j2ee/javaserverfaces/1.sun.2 : http://java.1/docs/tlddocs/index. 1.xml file.DefaultResourceResolver A list of URLs (separated by ".oracle. Create the subscription.jsp file.xml file. Example: /faces/*.dev. facelets.2 : http://java. In the case where an URL is not managed by Facelets.1/docs/api/index.sun. The value 1 allow to prevent the compilator to check if there are changes once the page is compiled.1 : http://java. This rule must be declared to go from subscription. Create a new JSF Projet 2.html Oracle ADF : http://www.0 which includes a tutorial for JSF 1.REFRESH_PERIOD Allow to define the minimum time interval that must wait the compilator before to check if a page should be recompiled (if there are any changes).java.sun. Create a new navigation rule in the faces-config. 1. This page will display the given name on the subscription. This one must be stored in the user session.1: http://java. If nothing is precised.html JSF javadoc: JSF 1. the parent default view (JSP) is used.com/javaee/5/docs/tutorial/doc/index.jsp file. Check the configuration of your web.sun.entity package.") that will be managed by Facelets.html Sun tutorial for JEE 5.sun. This one is a javabean with the following attributes : long id String name String description java. in the com. if you specify URLs.html Sun tutorial for J2EE 1.util.html Practices With this Exercice book.com/j2ee/javaserverfaces/1. Be careful.impl. you'll learn to : How to setup a web application with JSF Create a CRUD (Create Read Update Delete) application Use advanced JSF technology like RichFaces of Facelet Create your first JSF project With this exercice.html JSF 1.2/docs/api/index.xml that your servlet-mapping for JSF match this pattern <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> 9.com/technology/products/jdev/htdocs/partners/addins/exchange/jsf/index.net/ MyFaces homepage: http://myfaces. 8.VIEW_MAPPINGS Bibliography JSF tags documentation: JSF 1.RESOURCE_RESOLVER facelets. The default value is 2. the mapping to the servler FacesServlet should be mapped for several types of files. you are going to create the same JSF application as the one seen in the course. 5. Declare your javabean in your faces-config.com/j2ee/javaserverfaces/1. Launch your application Create the CRUD application Create all the business part of the application for creating a CRUD application.com/j2ee/1.sun. Create the configuration. Create your javabean User 4.4/docs/tutorial/doc/index. Create a new JSF project on your EDI 2. every requests will be managed by Facelets.4 which includes a tutorial for JSF 1.aspx?lecture=814&PM=True Page 97 of 100 .labosun.jsp file to confirmation. Allow to specify a custom ResourceResolver. The default value is: com.jsp file.org/index.2/docs/tlddocs/index. 6.facelets.xml file 3.html JSF 1.com/j2ee/javaserverfaces/1.jsf. Check in your web.Date creationDate https://www.xhtml 17/10/09 18:17 facelets.2: http://java.jsp file.campus-booster. 7.net/Booster/Pages/lectureSimpleViewer.

This one must have the following methods : public public public public public Movie addMovie(Movie m).impl package named MemoryMovieDao.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 int mark 3.xml file and try to realise theses navigations rules.campus-booster. 1. } public void updateMovie(Movie m) { } public void removeMovie(Movie m) { if(movieList.labosun. edit. } public Movie findMovie(long id) { for(Movie m : movieList){ if(m.jsf.remove(m).dao.aspx?lecture=814&PM=True Page 98 of 100 . you'll create the navigations rules.jsp.jsp</to-view-id> https://www. } Create the navigations rules For the MovieManager project.jsp. } return m. void removeMovie(Movie m).jsp. Create a new class in the com. list.add(m). Movie findMovie(long id). } public Movie addMovie(Movie m) { if (m != null) { m. Open the faces-config. Create a new interface in the com.net/Booster/Pages/lectureSimpleViewer. } } return null.setId(index++).jsp</from-view-id> <navigation-case> <from-outcome>list</from-outcome> <to-view-id>/list. Implements all the methods like this : private List<Movie> movieList.movieList = new ArrayList<Movie>(). movieList. Your navigations rules should look like theses navigations rules : <navigation-rule> <display-name>add</display-name> <from-view-id>/add.jsp file : <meta http-equiv="Refresh" content="0.jsf.contains(m)){ movieList. This class must implements the IMovieDao interface.URL=faces/list. void updateMovie(Movie m). Create 4 jsp files : index. } } public List<Movie> getAllMovies() { return movieList. private long index = 1. Create the getters and the setters for theses attibutes. 5.jsp.jsp file must be an HTML redirection to the list.dao package named IMovieDao.getId() == id){ return m. The index.labosun. add.jsp"> 2. public MemoryMovieDao() { this. 6. 4. List<Movie> getAllMovies().

labosun. } } add. 1.sun.org/TR/html4/loose.labosun. In this managed bean. } ////// ADD PART /////// /** * Get the current item to add * @return */ public Movie getAddItem() { if(addItem == null) addItem = new Movie().SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 </navigation-case> </navigation-rule> <navigation-rule> <display-name>list</display-name> <from-view-id>/list.jsp</from-view-id> <navigation-case> <from-outcome>list</from-outcome> <to-view-id>/list.dao.w3.jsp form with jsf markup.java package com.com/jsf/html" %> <%@ taglib prefix="f" uri="http://java.jsp</from-view-id> <navigation-case> <from-outcome>edit</from-outcome> <to-view-id>/edit. Correction MovieManaged.labosun.labosun.MemoryMovieDao. } /** * Insert in the datasource with the add item * @return */ public String insert(){ dao.net/Booster/Pages/lectureSimpleViewer.sun. you have to create a new Managed bean named MovieManaged and stored in the session to manipulate your created Movie (using the DAO layer : IMovieDao). You have to provide fields to theses Movies's attributes : Name Description Author Example 1.managed.jsf.entity.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.addMovie(getAddItem()).dtd"> <%@ taglib prefix="h" uri="http://java.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <display-name>edit</display-name> <from-view-id>/edit. if this one is non existing. private IMovieDao dao.Movie. the current instance of the item to add 2. return addItem. /** * @author Yakanet */ public class MovieManaged { private Movie addItem.impl.jsf.aspx?lecture=814&PM=True Page 99 of 100 .IMovieDao. Method public Movie getAddItem() Description This one will return the current instance of the item to add. return "add".jsf.campus-booster.jsp</to-view-id> </navigation-case> </navigation-rule> Implements the add method Let's create the web page to create a new Movie in your database.labosun.01 Transitional//EN" "http://www.jsf. create 2 attributes : Movie addItem IMovieDao dao Create two methods : Table 1.com/jsf/core" %> https://www. import com.managed package.jsf. import com. this method have to create it public String insert() This method will insert in the DAO layer. Create the add. public MovieManaged() { dao = new MemoryMovieDao(). import com. addItem = null.dao. In the com.

Method public DataModel getModel(). In the add. width:150px. } </style> </head> <body> <f:view> <h:form> <h2>Add</h2> <div> <div> <h:outputLabel value="Name" for="name" /> <h:inputText id="name" value="#{movie. Add a rich inputNumberSlider to the add. public Movie getEditItem() public String edit() public String update() public void delete() Description Create if not existing a DataModel object containing all the created Movies Return the current editing object. Add a validation constrain on the name field.jsp page Manipulate RichFaces Add some ajax features to your application 1. public int getNumberElement() Return the size of the existing movies in the DAO layer Create some validation rules Manipulate the valudation rules and the life circle of JSF 1. Add a rich calendar to the add.addItem. In the list.jsp page.campus-booster.name}" /> </div> <div> <h:outputLabel value="Author" for="author" /> <h:inputText id="author" value="#{movie. Set the current editing object Update the DAO layer with the current editing object. This method create this object if it not existing. charset=UTF-8"> <title>JSP Page</title> <style type="text/css"> label{ float:left. Do the same for the edit.js form. 5. Delete operations In your managed bean.jsp page.jsp page Use Facelet Realise the whole exercice with the facelet library Realise the whole exercice with the facelet library https://www. add the following methods : Table 2.net/Booster/Pages/lectureSimpleViewer. the maks must be set with a number between 0 and 20 2.author}" /> </div> <div> <h:outputLabel for="description" value="Description" /> <h:inputTextarea id="description" value="#{movie. Get the richfaces libraries and add them to your web project.addItem. Add a cancel button to go on the list. Delete in the DAO layout the selected item in the DataModel.jsp field use the RichFaces DataTable component to add some feature to the existing dataTable : Add a sort feature Add a datascroller to have only 5 items visible. Do the same operations for the edit.description}" /> </div> <div> <h:commandButton action="#{movie. Update.addItem. Display all the error if one of theses constraints aren't respected 4.SUN TECHNOLOGIES: JAVA ENTERPRISE EDITION 17/10/09 18:17 <html> <head> <meta http-equiv="Content-Type" content="text/html.jsp page 5. 2. add a field Mark. this one must be required 3. 4.insert}" value="Add" /> <h:commandButton action="list" value="Cancel" immediate="true" /> </div> </div> </h:form> </f:view> </body> </html> Realise the complete CRUD operations Let's add to the application the Read. This one must be linked to the mark attribute of the Movie class Add a validation constraint on this field (validateLongRange). 3.aspx?lecture=814&PM=True Page 100 of 100 .