Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  


AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

What Is JBoss Seam?

windows

+ Font mai mare | - Font mai mic



What Is JBoss Seam?




seam  (sem) n.

A line  of junction   formed  by sewing  together  two  pieces of material   along  their margins.

A similar  line, ridge, or groove made  by fitting,  joining,  or lapping  together  two sec- tions along their edges.

The preceding definition1     of seam is usually  used  when  discussing   sewing.  However,

this definition   also fits the latest  in frameworks   from JBoss—JBoss Seam.  JBoss Seam  is a

framework  that brings together   existing  Java Platform,  Enterprise Edition  ( Java EE) stan- dards to enable  them to work as an integrated solution.   At its core, the Seam  framework ties the Enterprise JavaBeans  3 (EJB3) and JavaServer  Faces ( JSF) specifications.   How- ever, Seam  does  not just stop  there—it will also join together   other component models that you may be used  to, such  as jBPM, Drools,  and more  that we will get into as the

book progresses.

When  I mentioned EJB, you may have been taken  aback  with fear or may have started shaking  your head profusely. Although  EJB 2.1 had some  negative  connotations, especially  regarding   the way it relates  to stateful  session  beans (SFSBs) and entity  beans (EBs), any negative  feelings  about it should  be reexamined   today.  With the new EJB3 specification,   EJBs have become  lightweight  plain  old Java objects  (POJOs) that do not require  as much of the plumbing   as before.  Hopefully  those  of you who may harbor negative  feelings  toward EJB3 will review and revise those  feelings  as you see how Seam enables  you to not only cut development    time  but also more  clearly separate your busi- ness  logic and presentation tiers by cutting  out the connecting   code  (for example,  Struts actions)  normally associated   with web frameworks.

For years developers   realized  that the JavaServer  Pages ( JSP)/servlets   paradigm was not enough  to create  enterprise-level web pages.  That model  provided the capability  for a web tier that could  pass  objects  from the client  to the server,  but essentially  that was it. For most  developers,   this simple  paradigm was not enough;  more-complex    operations

were needed,   and developers   found  themselves   writing  infrastructure code  to deal with

1.    https://www.thefreedictionary.com/seam                                                                                         1


the shortcomings    of the Servlet specification.   Eventually,  all the ideas  learned from cre- ating  custom  infrastructure code  resulted  in the web frameworks   we know today,  such

as Apaches Struts and Tapestry,  OpenSymphonys WebWork,  and so forth. The Java com- munity  also got together   and through the Java Community   Process  ( JCP) created the JSF specification   to tackle  some  of the issues  raised  and deal with the shortcomings    of the Servlet specification.

Even though  we now have web and business   tiers with improved   functionality,   we have still been forced  to create  the plumbing   code  needed to connect   them together. With Seam,  however, these  two areas  can now focus more  exclusively  on what  they do best—presentation and business   logic.

What Does Seam Buy You?

When  picking  up this book,  one of your first questions   should  be, Why do I even need Seam  if I have EJB3 and JSF already? After all, they were designed   to simplify  the process of creating  web applications.   What is the benefit  of using  the Seam  framework with these  components if they have already  taken  care of much of the plumbing   that was required   before?

The answer  lies in what  you are trying to accomplish.   To be useful,  your application has to be a multitiered   application   that uses specific  components for the presentation, business,   and persistence   tiers. Before, you may have accomplished    this with a combina- tion of Struts (presentation),    Interface21s Spring (business),   and JBosss Hibernate (persistence)   frameworks.   Now, following  the Java EE specification,   you will be using  JSF (presentation),    EJB3-SB (business),   and EJB3-EB (persistence).   As before,  each  of these components requires  lots of glue to link them together  to talk to each  other. Throughout this book I will show you how Seam has transformed this messy  gluing  you had to do before  into a now seamless  process.

Three-Tier Architecture

Any beginner   may ask not only, Why do we need all this?” but also, Where  does Seam fit into the equation?”   Since about 1999, standard development    practice in Java EE was to divide your application   into three distinct  tiers: presentation, business,   and persistent tiers, as illustrated in Figure  1-1. ( Java EE was then known  as J2EE. It became  Java EE after version  1.4 of the Enterprise Edition).


Figure 1-1. The three-tier  Java EE architecture

These  tiers are defined  as follows:

Presentation  tier: The presentation tier encompasses    everything  from the Hypertext Markup  Language  (HTML) page to objects  controlling the request,  such  as Struts Action  classes  or JSF backing  beans. Everything  in this tier deals  with communication to the client—be  it a web page or BlackBerry.

Business  logic tier: The business   logic tier is where  you make  your business   decisions;

it contains   the logic of the application.   Also, this is where  the business   processing and (if needed)   the database transactions occur.

Persistence tier: The persistence   tier represents the interaction   with the database. This is where  you maintain data access  objects  (DAOs), Hibernate DAOs, or your entity beans. These  classes  can be either  database specific  or nonspecific,   depending on what  you need.  This tier may also contain  your database domain  objects.

Three-Tier Architecture with Seam

Now you will take a look at the same  architecture    when  using  Seam.  Figure  1-2 shows  the injection  points  of Seam into the tiers; notice  that it encompasses    every tier.


Figure 1-2. The three-tier  Java EE architecture  with Seam

In Figure  1-2, you can see that Seam wraps  the components by using  annotations to declare  the POJOs to be wrapped. Then  Seam identifies  those annotated POJOs and

binds  the components across  the tiers by using  interceptors.   This allows a smoother   tran- sition  between tiers. Usually  the binding  and connecting   between the tiers is much rougher in Java EE architecture    without  Seam. This allows you to then focus your devel- opment on the business,   presentation, and persistence   tiers without  worrying  about making  them interact.  Chapter  5 covers  in more  depth the interception    of the Seam com- ponents as well as their  life cycle.

Component Choices

As you know,  and as I pointed out earlier,  there are many  different components that can work for the various  tiers. So why should  you use JSF + EJB3 + Seam? The simple  answer is that the first two are the new standard. However,  there are additional,   more-solid answers  than that as well. In this section  and in the following  few chapters   you will more closely examine  the usefulness   and clean  implementations     (due  to being  POJOs) of

these  components.

Why JSF?

JSF is now a Java standard from the JCP for presentation tier development.    Now, just because  something   is a standard does  not necessarily   mean it is the best  choice,  but that you should  factor  it into the equation.   JSF being  part of the JCP will guarantee that there


will always be support from an army  of developers   with skill sets specific  to its imple- mentation. Along with this support, there are also a wealth  of built-in  tools from vendors and third-party programs for creating  robust JSF pages.  Plug-ins  are being  cre- ated,  and even more  are planned to help  make  JSF pages  as easy as possible  to create  by having  drag-and-drop functionality   for the various  integrated development    environ- ments (IDEs). There  are also multiple  JSF implementations     to choose  from.  Apaches MyFaces  is what  JBoss uses for its JSF implementation     and is what  we will be using throughout the book.

Another  positive  with JSF is its ability  to handle  multiple  presentation tier types. Yes, many  other frameworks   can be hacked  to do that as well, but this is out-of-the-box    sup- port. This is achieved  through JSFs presentation tier component-based architecture. Although  the JSF pages  still use tag libraries  for the display,  the component orientation   of the JSF components makes  them more  than just simple  user interface  (UI) pieces.  The libraries  are naturally then more  involved  with each  other.

Another  advantage   to JSF is that it simplifies  the development    of code  that is called from the client  page.  In JSF, these  listeners  are referred  to as backing  beans. As I said ear- lier, JSF is partially independent from the servlet  context,  so the backing  beans used  can be regular  POJOs with no knowledge  of the Servlet specification.   I say partially  because they can have access  to the Servlet specification   if it is directly  declared.

Finally, JSF continues   to make  inroads  into the community   and with Struts. Many of the former  Struts developers   used  their  knowledge  of what  they did right and wrong  in the past to help create  the JSF specification.

Why EJB3?

EJB3 provides just about everything  you could  want  for business   logic and presentation tiers. You get enterprise-level state-managed    classes,  Java Message  Service ( JMS) listen- ers, and database-level    objects.  Now, most  of you may think,  Well, so did EJB 2.1; why do I need EJB3?” Well, this is all provided without  the need for Extensible  Markup  Language (XML), and all your classes  are still POJOs. You no longer  have the overhead of multiple interfaces   for creation  and remotes,  no more  convoluted   deployment   descriptors,   and no more  stub creations.   Also, like JSF, this is an industry standard, so you also get the regular cadre  of developers   working  on it as well as different implementations.



Why Seam?

The simple  answer  to why we are using  Seam is to create  simplicity  from complexity. Regardless  of how easy it is to implement   JSF and EJB3, they still require  you to create backing  beans to allow your presentation tier to talk to your business   logic tier. With JSF, you have to write extensive  XML files telling  the presentation tier what  kind of domain objects  to expect.  By using  Seam,  you can remove  extra coding  and focus more  on the parts that matter—the   presentation and business   logic.


Seam  does  this not by creating  an extra class such  as a JSF action  listener,  but by using  Java annotations. Seam  allows you to create  a seamless  transition between appli- cation  tiers by utilizing  metadata in the form of Java annotations to define  how the presentation and business   logic tiers can talk to each  other. In addition,   Seam  also

allows you to define  EB domain  objects  to be used  on the presentation tier. The question then becomes,   How are we just removing  classes? or Were these  classes  really needed before? After working  with many  web frameworks   on many  projects, I have noticed  that often  what  your action  listeners  are doing  is just translating presentation tier data to some business   logic tier object,  validating  that data,  and then sending  it over to the business   logic tier for processing. If they are doing  more  than that, you are often  mixing business   logic into your presentation tier. Seam  helps  you skip this step.

Of course,  there are times  where  the presentation tier needs  to do a bit more,  so, if you wish, you can also use regular  JavaBeans  as your annotated objects  as well. If you do this, note that the only reason  to do so is because  you need to prep the data before  send- ing it over to the business   logic tier. Based on what  I have said thus far, Seam  is not adding any features  but just taking  a few steps  away—which,   by itself, still makes  Seam  a valuable  tool. However,  it also does  add some  valuable  context-management      abilities, which  allows you to have features  such  as wizards  on your page without  having  to add a bunch of extra plumbing   code. We will get into the details  of this in later  chapters (Chapters 5, 6, and 7). Hopefully,  however, you can already  start to see the value of not only Seam,  but the combination    of Seam,  EJB3, and JSF.

Seam Environment Requirements

Because  Seam is dependent on JSF and EJB3, it has a few more  needs  than frameworks such  as Spring or Struts. Specifically,  Seam requires  the following:

 You have to use Java 5 or greater  on the front end,  because  Seam relies heavily on annotations provided by Java 5 or higher  implementations     of Java Specification Request  ( JSR) 250.

 You have to use a JSF implementation     for the presentation tier. This means either using  an application   server  that supports it or using  an open source  provider of JSF such  as Apaches MyFaces.

 For the most  part, you need to have an application   server  that uses EJB3. Chapter  9 discusses  alternatives   to using  EJB3. However,  it is best to assume  that you are either going to be able to use EJB3 now or in the near future.


Hello World Example

So before  you dive into the intricate details  of Seam and the functionality   around it, lets take a quick look at building  a simple  Seam application.   As I have said, it provides the glue between the presentation tier and the business   logic tier, specifically  EJB3. However, in reality,  your business   logic tier does not have to be EJBs—it can just be plain  Java- Beans. So lets look at a Hello World application   done with Seam.  In this example,  a simple JSF page will call the JavaBean to get the text of outputText   that has been initial- ized. We will start with the Seam-annotated JavaBean in Listing 1-1.

Listing 1-1. Our JavaBean, HelloWorldAction.java,    with Seam  Annotations

package  com.petradesigns.helloworld;

import  org.jboss.seam.annotations.Create;

import  org.jboss.seam.annotations.Name;

@Name('helloWorld')

public   class HelloWorldAction   implements  IHelloWorld   

public   String getOutputText()     

}

As you can see, this is a fairly straightforward Hello World JavaBean.  The first @Name

annotation defines  for us that this is a Seam component with the name of helloWorld.  You will then notice  that there are two methods. The init() method has an @Create annota- tion signaling  that this method should  be called  upon instantiation    of the JavaBean.  The public  method getOutputText()    can be used  to retrieve the output text.

Now that we have the JavaBean,  we will create  the JSF page needed to retrieve it. The page is defined  in Listing 1-2.


Listing 1-2. Our JSF Page, helloWorld.jsp,   to Display Hello World

<%@   taglib uri='https://java.sun.com/jsf/html' prefix='h'    %>

<%@   taglib uri='https://java.sun.com/jsf/core' prefix='f' %>

<f:view>

<h:outputText    value='#'/>

</f:view>

This is a JSP page; more  specifically,  it is a JSF JSP page. The first part contains   the standard tag library  definitions,   and the second  part defines  the <f:view>  component. This is a standard component to encapsulate    any JSF functionality   and is required.

Finally, our #      references   the method outputText   on the Seam component helloWorld  that we defined  previously. When  this page is run, it gives us the output shown  in Figure  1-3.

Figure 1-3. The Hello World screen shot

This is all the code  it takes  to create  a Hello World example  by using  JSF and Seam. This small application   consists  of a presentation and business   tier, even though  our busi- ness tier is not really doing  much.

Note If we wanted to make the JavaBean an EJB3 object, all we would have to do is add the

@Stateless   annotation to the class description of the JavaBean.

One of the first things  you should  notice  is our JavaBean representing the business logic. Not only can it be a POJO, but there is nothing  in it making  it interact  exclusively with the presentation tier; nor is there anything  on the presentation side telling  it to interact  exclusively  with a Seam component. Seam is handling  all that messy  middle work usually  needed to pipe  between the tiers. The end result:  you are able to put the bulk of your effort in building  a solid business   logic tier as opposed   to making  those objects  available  to the presentation tier.

I strongly  advise  you to use my build  script  included   in the source  to create  this code because  there are some  intricacies on how to create  JSF + EJB3 + Seam that may not be entirely  obvious  to you yet. These  intricacies are explained   more  clearly in Chapter  5. For now, this can give you a bit to play with.


Introduction to MVC Architecture

If you are familiar  with web application   design  in Java, the MVC pattern is probably fairly well known  to you. However,  if this is your first time  writing  a web application,   you should follow along  closely. This is essentially  the pattern that has been followed  for designing  most  web frameworks.

This section  presents the MVC architecture    and gives examples  of various  implemen- tations  of it, including   JSF. For those  who are new to web applications,   this should help provide some  background into how it works.

Basics  of MVC Architecture

If this is your first attempt at web development,    the concept   of Model-View-Controller (MVC) may be new to you. It is the basis  for most  web application   development    today. The core principle is to separate your business   data from your view components, and then have the ability  to translate the data back and forth, as illustrated in Figure  1-4.

Figure 1-4. A diagram of the MVC architecture

The following  are the definitions   of the MVC parts:

Model: This represents data in the business   logic tier and the business   rules  defining interactions   with that data.

View: The view renders  the contents of the model  for the presentation tier.

Controller:  The controller translates the model  into the view. The translation will be performed by POST/GET requests   from the Web.


Frameworks

A variety  of web frameworks   have come  out over the last few years to implement   MVC. For this book we will be using  MyFaces,  an open source  implementation     of the JSF speci- fication.  However,  it would  be handy  to learn about a few of the others  as well.

Fundamentally,    all web frameworks   work the same  way. They all, in some  way, extend  the Servlet specification.   How they usually  differ is in how much you are aware that they are extending   this specification.   When  using  Struts 1.x and Spring MVC, you are fully aware  that your classes  are part of the Servlet specification.   There  are servlet- specific classes  such  as HttpServletRequest     and HttpServletResponse     given to you. When using  frameworks   such  as Struts 2 and JSF, you are not as aware.  In general,  the servlet- specific  objects  are fairly well hidden and you have to explicitly  ask for items  such  as HttpServletRequest     and HttpServletResponse.    Finally, with frameworks   such  as Tapestry, you are not really aware  of the specification   at all except  through configuration   files.

Next you will take a look at each  of these  frameworks.   This small preview gives you an idea of what  is out there and has been tried and will hopefully  give you insight  about why you do not have to worry about the nitty-gritty   of these  when  using  Seam.

Struts

Struts, one of the first web frameworks,   has definitely  proved to be the most  popular  one out there. It works by having  a front controller servlet  call action  classes.  The data from the screen is passed  into the classes  via an ActionForm. With Struts 1.x versions,  the user was fully aware  that they were working  in a presentation tier—and  the classes  were con- crete,  not POJOs. Much of this has been redressed   with Struts 2; however, Struts 2 does not have nearly  the success  and is not used  as much as Struts 1.x.

Spring MVC

Spring MVC is a more  recent entrant to the MVC game.  Spring MVC is distributed with the regular  Spring package  and can perform business   logic as well for a complete   Java EE framework.   However,  Spring MVC is not as new as the rest of Spring. It does provide vari- ous ways of interacting   with the presentation tier, and if you are looking  for a low-key approach, this can work well. However,  Spring MVC does not seem  to have the robust- ness of the other web frameworks   such  as JSF, Struts, and Tapestry.



Tapestry

Tapestry  is another web framework  that has been around for a long time. The major  recent upgrade  of Tapestry  4 is powerful. One of its biggest  advantages   is that, contrary to JSF and most  other web frameworks,   your Tapestry  classes  have no knowledge  that they are part of a web state because  your controller classes  (pages  in Tapestry)  have no knowledge  of the


request  or the session.  However,  unlike  Seam, these  pages  are not POJOs but they imple- ment the IPage interface.  Another  advantage   of Seam is the use of Object-Graph Navigation Language  (OGNL) for its presentation tier. This allows HTML and Java developers   to create HTML pages  that can be translated to dynamic  code when  run in the application   server,

but if viewed with a standard web browser outside  the application   server,  the pages  will still be viewable.  This is not normal behavior  for most  web application   servers.

A Seam-Tapestry   combination    would  be great.  Unfortunately,    there is no plan  to build  one at this time.

JSF

Java Server Faces ( JSF) is a JSR standard for presentation tier development.    Like most other frameworks,   it provides a separation   between the presentation tier and the action listeners.  Unlike  most  other web frameworks,   the actual  presentation tier can vary—it does not have to be a JSP-type  page because  JSF uses a component model  to display  the presentation tier. Your presentation tier can therefore switch  more  easily between a web page,  XML page,  or Java Micro Edition  (ME) page.  Also, because  this is a standard, there are a variety  of implementations     of vendor support for it.

Java 5

Java 5, also known  as Java 1.5.0, is the latest  version  (at the time of this writing)  released from Sun Microsystems—which    many  thought was a long time coming.  Java 5 adds  items such  as annotations and generics,  which  many  developers   had wanted  for years. This latest release  adds  15 JSRs and about 100 other major  updates. This impressive   level of enhance- ment and change  reflected  such  a maturity that the external  release  was given a Java 5 designation.   Table 1-1 lists the JSR enhancements for the release  of Java 5; unfortunately,    I cannot list all of them within  the constraints   of this book. However,  a few of the enhance- ments are good to know, and others  are important in order  to understand how to use EJB3 and Seam. If you want  to read a complete   list of features,  I suggest  consulting   the Sun site, https://java.sun.com/j2se/1.5.0/docs/relnotes/features.html.

Table 1-1. JSRs for the Java 5 Release

JSR Number

JSR Name

URL of Specification

003

Java Management    Extensions

https://jcp.org/en/jsr/detail?id=3

( JMX) Specification

013

Decimal  Arithmetic  Enhancement

https://jcp.org/en/jsr/detail?id=13

014

Add Generic Types to the Java

https://jcp.org/en/jsr/detail?id=14

Programming   Language

Continued


Table 1-1. Continued

JSR Number                                                                                                         JSR Name        URL of Specification

028                                                          Java SASL Specification                          https://jcp.org/en/jsr/detail?id=28

114                                                          JDBC Rowset Implementations                  https://jcp.org/en/jsr/detail?id=114

133                                                          Java Memory  Model  and Thread           https://jcp.org/en/jsr/detail?id=133

Specification   Revision

160                                                          Java Management    Extensions                       https://jcp.org/en/jsr/detail?id=160

( JMX) Remote  API 1.0

163                                                          Java Platform Profiling  Architecture         https://jcp.org/en/jsr/detail?id=163

166                                                          Concurrency   Utilities                           https://jcp.org/en/jsr/detail?id=166

174                                                          Monitoring   and Management                        https://jcp.org/en/jsr/detail?id=174

Specification   for the Java Virtual Machine

175                                                          A Metadata Facility for the Java                      https://jcp.org/en/jsr/detail?id=175

Programming   Language

200                                                          Network  Transfer  Format for                                                                       https://jcp.org/en/jsr/detail?id=200

Java Archives

201                                                          Extending  the Java Programming                   https://jcp.org/en/jsr/detail?id=201

Language  with Enumerations, Autoboxing, Enhanced for Loops and Static Import

204                                                          Unicode  Supplementary                                https://jcp.org/en/jsr/detail?id=204

Character   Support

206                                                          Java API for XML Processing   ( JAXP) 1.3                https://jcp.org/en/jsr/detail?id=206

250                                                          Common Annotations   for the                       https://jcp.org/en/jsr/detail?id=250

Java Platform

Next I will go over where  to retrieve Java 5 and will discuss  language  features  that will help you understand and use Seam.

Downloading    Java 5

One of the biggest  requirements for using  Seam is that you have to use Java 5. This is pretty obvious  when  you realize  that Seam is entirely  implemented    in your code  with annotations and that Java 5 introduced us to annotations. Of course,  as indicated   in Table 1-1, there is a lot more  to Java 5 than annotations, and I want  to share  some  of the language  features  with you. However,  in order  to do that, you need to download   and install  Java 5 first.

Many computers   come  preinstalled with Java 5—all Apple OS X operating   systems, for example,  contain  Java 5 by default.  With Suns relatively  new installation   of Java, it runs as a service  and will update it for you. You can check  whether  you have the correct

4a2bcfb4faa892c3cbcf27f39e1c8d78


version  of Java by typing  java  –version  at a command prompt. If the response   indicates build 1.5 somewhere   in it, you have the right version.  The following  is an example  of a response   you might  receive  if you ran that command on an OS X operating   system:

Java(TM)  2  Runtime  Environment,   Standard   Edition (build 1.5.0_06-112)

Java  HotSpot(TM)  Client VM   (build 1.5.0_06-64, mixed  mode,  sharing)

If you do not see build  1.5, you will need to download   the latest  Java 5 Software Development   Kit ( JDK 5.0), formerly  known  as the JDK. The JDK is needed over the regu- lar Java Runtime Environment ( JRE) because  we plan  on actually  doing  development with it. You can download   it at https://java.sun.com/javase/downloads/index.jsp. At that page,  select  one of the JDKs at the top. Figure  1-5 shows  the download   page. You can choose  any of the downloads   in the highlighted   section  to get the Java 5 installation.

Figure 1-5. Screen showing  a highlight  of one of the three JDKs to download

The installation   of the software  should  be fairly straightforward;    if you have any problems with it, consult  the documentation on the Sun website.


Language   Features

As I said earlier,  it would  be difficult  to discuss  all the enhancements that have come  with Java 5. However,  to understand certain code  examples  later,  you need to know about the language  features  that have been changed   or added.  I will present each  of the language features  and provide example  code  so that you can successfully  use the features.  You will not necessarily   need to understand them all to use Seam. The only items  that are absolutely necessary   to understand are the annotations. However,  I still suggest  reading all of them. Most are designed   to make  your life simpler  and the code  cleaner.

Metadata (aka Annotations)

One of the biggest  additions   to Java 5—and  indeed  what  is the core to what  makes  Seam work—is annotations. Annotations   were partially derived  because  of the ever-increasing amount of XML. XML was used  for deployment   descriptors,   configuration   files, and so forth, but when  all was said and done, there were often  too many  XML files. Another problem associated   with XML files was that there was no compile-time    ability  to check that you wrote  the XML file correctly.  Finally, annotations allow us to make  more  classes POJOs and less reliant  upon implemented    objects.

Now, one of the interesting   things  about annotations is that, more  than likely, you will never  actually  have to write one. However,  that being  said, it is always good to know how to just in case.

With all the hype  I have just given them, the question   really should  be, What is an annotation?”   Listing 1-3 provides an example  of using  an annotation.

Listing 1-3. An Example  of Using an Annotation

import  javax.ejb.Stateless;

@Stateless

public class MyStatelessBean    

As you can see, this looks awfully like a Javadoc  tag. However,  it does much more than a Javadoc  tag. Annotations do not affect the semantics   of the program; they affect the way a program is treated by the tools running  it. So in the preceding code,  we have an example  of an EJB3 stateless  session  bean.  By using  annotations, we have transformed what  used  to be a complex  object  into a POJO.

For the purpose of this discussion   I am not going to describe  how to design  your own custom  annotation. You could  create  one, but then you would  also have to create  a framework  that will access  it. It is something   that can be valuable  but out of the scope  of our needs  for this book.


Generics

One of the biggest  headaches   I had recently  occurred   when  another team gave me an application   programming interface  (API) to use, and the API was full of lists with names that were not very descriptive.   Furthermore, many  names in the system  were similar  to one another, and the Javadoc  was quite  incomplete.   As a result,  I used  a lot of trial and error  in attempting   to add the right lists and to retrieve the right lists, and I received many casting  errors.  I am sure  just about every developer   has made this mistake  as well. You run your code  and then up comes  a ClassCastException    because  you casted  the wrong type of object  from the list. Having  errors  like this that are relatively  simple  to make  and that pop up only at runtime is unsafe.

The good news is that we no longer  have to worry about this with generics.  Now we can check  our collections   at compile  time.  Listing 1-4 is an example  without  generics.

Listing 1-4. An Example  of Iterating  Through  a Collection Without Generics



public void  sumWOGenerics(Collection    col) System.out.println(sum);

}

So if someone   was calling the method,   they would  have to know the details  of the

method to determine what  type of collections   to pass through to it. However,  Listing 1-5

shows  an example  using  generics.

Listing 1-5. An Example  of Iterating  Through  a Collection  with Generics

public void  sumWGenerics(Collection<Integer>       col) System.out.println(sum);

}


As you can see, when  using  generics,  the process is relatively  simple,  and the calling object  knows  exactly what  type to put into its collection.   But the method itself no longer has to worry about ClassCastExceptions     at runtime. The preceding generic  collection would  be read  as Collection  of Integers.

Another  concept   associated   with generics  is the ability  to return a class but specify it with a generic  instead.  For example,  think  of the Class  object.  There  is a newInstance() method on the object  that will create  a new instance   of that class. In general,  you use that by writing  something   like the following:

String s = (String)String.class.newInstance();

However,  by using  generics  you can eliminate   the casting.  This is because  now the method is defined  as follows:

T  newInstance()

where  T represents a generic  type. Many objects  built into the JDK, such  as the Class object,  have been retrofitted to support these  changes.  Another  important concept   to realize  about generics  is that they are implanted   by erasure—meaning     that, in practical terms, the check  is only at compile  time. They are not runtime-processed items  (C++ developers   might  want  to take note that the templating   I just showed  is very different from how it is implemented    in C++).

Enhanced for Loop

As you saw with the generics,  we were able to remove  the casting  and hard code  we knew would  work, or at the very least would  give us warnings  at compile  time.  However,  look- ing at the code  itself, it really does not look any less complicated.   In fact, you might  argue that it looks even more  complicated.   Fortunately,   Java 5 also brings an enhanced for each loop. Listing 1-6 presents the generics  example  using  the enhanced for loop.

Listing 1-6. Our Generics Example  with the Enhanced  for Loop

public void  sumWGenericsAndForLoop(Collection<Integer>     col) System.out.println(sum);

}

As you can see, this is much less complicated.   This will take your collection  and set

it to the variable  i, which  is of type Integer. So on each  loop it will go around storing  the


next value of the collection  into the variable  you defined.  This is much simpler  and much easier  to use, especially  if you want  to use embedded for loops. You can also use this technique on arrays  by replacing  your collection  with an array  of integers  (the rest of the code  would  look exactly the same—note   that this will work with primitive data types  as well).

Now, the only downside   to this is that if you try to remove  an element,   you cannot do it because  you do not have access  to the iterator.

Autoboxing

One thing  about the preceding code  that is slightly annoying is that we had to use

.intValue() to convert our value from an object  to a primitive. By using  autoboxing, you could  leave it out as in Listing 1-7.

Listing 1-7. Summation Method Using Autoboxing

public Integer addWAutoboxing(Collection<Integer>      col) System.out.println(sum); return sum;

}

We no longer  need to convert the integer  to a primitive value.  In this example,  the

code  is more  readable.   Imagine  a line that has a mix of multiple   integer  objects  and primitives adding  and subtracting. Now the code  will be much cleaner.  Also, not only can we downcast,   but we can also upcast.  Notice  in the preceding example  that the second-to-last    line is return sum, which  is a primitive even though  the method is returning an object.

As you can see, instead  of having  to use return new Integer(sum),    the compiler  will automatically   box the primitive integer  for you to an integer  object.  Now, with this ability you have to keep in mind a few things.  I showed  how easy it is to use autoboxing, so you should  use it in places  where  you were originally  going to do primitive-to-object transfor- mations.   However,  it should  not be done haphazardly, especially  on a method that may

be performance sensitive.

Typesafe Enums

Enumerated types  have been something   that many  C and C++ developers   have missed from Java. Well, fret no longer—they   are here and have been given good support. Before


(with Java), the only way to use enums was to create  a class and have it contain  a bunch of static  variables.  However,  even if you are familiar  with C and C++ enums, these  enums are different and much more  powerful. Instead of glorified  integer  holders,  these  enums are more  like objects,  and are even comparable   and serializable.   Listing 1-8 shows  an example.

Listing 1-8. An Example  of an Enum in Java 5

enum  Week  ;

Varargs

This step is designed   to save you time  rather than give you added functionality.   One step that often  occurs  in development    is creating  object  arrays.  There  are a variety  of reasons to use arrays.  A common   one is to send a variable  list of objects  over to a method call. Take, for example,  our concept   of summing   items.  Suppose you have a method that you want  to pass an unknown   number of arguments   to. In reality,  the only way to do it is by creating  an array and passing  it in that way. The method signature   would  look like that in Listing 1-9.

Listing 1-9. Passing an Integer Array for Our Summation

public int  sums(Integer[] values)

return sum;

}

However,  there is downside   to this. First of all, you may want  to send only one argu-

ment to the method.   In that case, you would  be creating  an array for nothing.   Second, even if you do want  to pass more  than one argument   to the method,   it can look quite ugly. Check it out:

int sum = sum(new Integer[] );

This is quite  difficult  to look at, especially  if we were passing  items  longer  than just numbers. Fortunately,   when  using  autoboxing, calling the method is not as complicated


because  we do not have to create  new Integer objects  for each.  By using  variable-length arguments   (varargs),  there is an easier  way to do this. This is a way of telling  the method that there is a variable  number of values  of a particular type. For example,  in the preced- ing example,  the method would  change  as shown  in Listing 1-10.

Listing 1-10. Passing the Values as Varargs for Our Summation

public static int sum (Integer  values)

return sum;

}

As you can see, the method body stays the same,  and we can simply  treat the values

as an array as we did before.  However,  the real ease comes  when  calling the method.   Now in order  to call it, all we have to do is write the following:

int sum = sum(1,2,3);

This tells the method that you can have a variable  number of values. That value object inside  the method itself will be treated as an array.  However,  now you do not have to create  the array yourself;  you can call the method in a much more  elegant  manner. Although  I like this functionality,   I can see it is easy to abuse.  In general,  most  methods should  know how many  arguments   they are passing  into the method.   Logging methods, however, or summation methods like those  in the preceding code  do not necessarily need to. Just be careful  when  implementing    this step.

Static Import

Another  new ability  that you should  use only on certain occasions   is the ability  to have static  imports.  Static imports  are basically  as they sound:  they are the importing   of static- level variables.  Take, for example,  E on the Math object.  To call it, you would  use Math.E in your code. With static  imports,  all you have to do is call E but then include  the import of this at the top of the class:

import   static  java.lang.Math.E;

This can be very useful  in a class that is doing  a lot of calls to the import in the class, and especially  in something   like a Math class, where  on one line you would  have


to reference   static  variables  often.  This would  cut out the amount of code  written so that it becomes   cleaner.  However,  be careful  in the use of static  imports  because   track- ing where  this variable  comes  from  by looking  at the code  can be confusing.

POJOs

Last, but definitely  not least, are POJOs, a term I have used  throughout this chapter and will continue to use even more  throughout the book. POJOs not only are the basis  for Seam, but are starting  to be used  by all web frameworks.   POJO, which  as I stated earlier stands for plain  old Java object, is an acronym  that was coined  in 2000 by Martin Fowler, Rebecca  Parsons,  and Josh MacKenzie.  The term describes   a Java object  that does not implement   any framework  design  pattern. Often you see them used  as domain  objects  or even business   objects.  Instead of having  to extend  objects  and make  the classes  conform to a specification,   they are looser.  In fact some  frameworks   such  as Spring wrap the trans- actioning   and other business   concepts   on the object  by using  XML to define  which

POJOs are what.

Annotations   on POJOs

The use of annotations is what  gives POJOs their  magic.  As I said earlier,  annotations add discrete  functionality   to the code  without  forcing  the class to implement   any interfaces

or be subclassed.   The area  in which  we are going to use POJOs the most  is with EJB3, as you will see in Chapter  4. This can still be controversial because  POJOs do exhibit  frame- work-like  definitions   in the class; however, with annotations the annotated methods and classes  have their  business   functionality   invoked  only if they are run in the correct  con- tainer.  As you will see when  you read  further in the book, POJOs have great functionality and flexibility for Java EE application   development.

If you want  to learn more  about POJOs, I suggest  checking  out Brian Sam-Boddens book, Beginning  POJOs (Apress, 2006).

Configuring Your Server

To use Seam  with our examples,   you have  to download   a few resources,   mainly  JBoss Application   Server (AS), Apache  Ant, and MySQL. If you do not have  these  items already, I have  included   some  information in the appendices   on how to download   and configure  them.


Summary

This chapter introduced Seam and the underlying   frameworks   that it depends on—JSF

and EJB3. The basic  knowledge  provided in this chapter will be enhanced in Chapters   3,

4, and 5. This chapter also defined  what  a basic  MVC framework  is and discussed   the top frameworks   used.  In addition,   it introduced Java 5 and POJOs, which  will help you start understanding    some  of the concepts   used  by Seam.  By now you should  be ready  to go with your development    environment. The next chapter covers  the basics  of web design and outlines  our sample  applications.   From  there you will dive into development.






Politica de confidentialitate



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 652
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2022 . All rights reserved

Distribuie URL

Adauga cod HTML in site