Java EE 6 Hands-on Lab

47
Java EE 6 Hands-on Lab Java EE 6 Hands-on Lab Devoxx 2011  Arun Gupta blogs.oracle.com/arungupta, @arungupta Oracle Corporation 1

description

Java EE 6 Hands-on Lab

Transcript of Java EE 6 Hands-on Lab

  • 5/26/2018 Java EE 6 Hands-on Lab

    1/47

    Java EE 6 Hands-on Lab

    Java EE 6 Hands-on LabDevoxx 2011

    Arun Guptablogs.oracle.com/arungupta, @arungupta

    Oracle Corporaton

    !

  • 5/26/2018 Java EE 6 Hands-on Lab

    2/47

    Java EE 6 Hands-on Lab

    Table of Contents

    1.0 Introduction..........................................................................................................................................3

    1.1 Software Downloads....................................................................................................................... 32.0 Problem Statement............................................................................................................................... 33.0 Build the Template Web pplication................................................................................................... !

    !.0 "enerate #P $ntities from the Database Table...................................................................................%

    !.1 Wal&'throu(h the #P $ntities and )efactor to Simplif* ............................................................... +%.0 ,uer* the Database from a Ser-let......................................................................................................

    /.0 cti-e )edeplo* to Preser-e Sessions............................................................................................... 11

    +.0 ,uer* the Database usin( $#B and )efactor the Ser-let .................................................................. 13.0 dd alues to the Database usin( $#B use Bean alidation onstraints ........................................1!

    .0 T*pe'safe ritieria ,uer* usin( #P2 4etamodel.............................................................................1+

    10.0 achin( usin( Sin(leton $#B and 5Schedule to Pre'fetch Data ................................................... 20

    11.0 4 usin( #S6276acelets'based -iew.............................................................................................2112.0 D)8 usin( #S62 omposite omponent.........................................................................................2/

    13.0 Declarati-e 9a: to )etrie-e Partial alues from the database ........................................................2

    1!.0 Publish $#B as a )$STful )esource usin( #;')S........................................................................321%.0 #erse* lient PI to ccess the )$STful )esource ....................................................................... 3/

    1/.0 In9ect Beans usin( DI ,ualifiers................................................................................................... 3

    1+.0 ross'cuttin( oncerns usin( DI Interceptors.............................................................................. !11.0

  • 5/26/2018 Java EE 6 Hands-on Lab

    3/47

    Java EE 6 Hands-on Lab

    1.0 Introduction

    #$e Java EE 6 plat%orm allo&s 'ou to &rte enterprse and &eb applcatons usng muc$

    lesser code %rom ts earler versons. (t brea)s t$e *one s+e %ts all approac$ &t$ ro%les andmproves on t$e Java EE developer productvt' %eatures tremendousl'. everalspec%catons l)e Enterprse Java0eans 1.!, Javaerver 2aces ".3, Java A( %or 4E#%ul5eb ervces !.!, Java ersstence A( ".3, ervlet 1.3, Contets and 7ependenc' (n8ecton!.3, and 0ean 9aldaton !.3 ma)e t$e plat%orm more po&er%ul b' addng ne& %unctonalt'and 'et )eepng t smple to use. :et0eans, Eclpse, and (ntellJ provde etensve toolng %orJava EE 6.

    #$s $ands-on lab &ll buld a t'pcal 1-ter end-to-end 5eb applcaton usng Java EE 6tec$nologes ncludng JA", J2", EJ0 1.!, JA;-4 !.!, ervlet 1, C7( !.3, and 0ean9aldaton !.3. #$e applcaton s developed usng :et0eans < and deplo'ment on Glass2s$

    1.!.!.

    #$e latest cop' o% t$s document s al&a's avalable at$ttps=//blogs.oracle.com/arungupta/resource/8avaee6-$ol-nov"3!!.pd%.

    1.1 Software Downloads

    #$e %ollo&ng so%t&are need to be do&nloaded and nstalled=

    J7> 6 or < %rom $ttp=//&&&.oracle.com/tec$net&or)/8ava/8avase/do&nloads/nde.$tml .

    :et0eans

  • 5/26/2018 Java EE 6 Hands-on Lab

    4/47

    Java EE 6 Hands-on Lab

    4E#%ul resource and s t$en accessed programmatcall'. #'pcal desgn patterns reured b'a 5eb applcaton l)e valdaton, cac$ng, observer, partal page renderng, and cross-cuttngconcerns l)e loggng are eplaned and mplemented usng d%%erent Java EE 6 tec$nologes.

    #$s applcaton uses a sample database t$at comes pre-con%gured n bot$ :et0eans *All

    and *Java EE do&nloaded bundled versons.

    Disclai!er##$s s a sample applcaton and t$e code ma' not be %ollo&ng t$e best practcesto prevent L n8ecton, cross-sde scrptng attac)s, escapng parameters, and ot$er smlar%eatures epected o% a robust enterprse applcaton. #$s s ntentonal suc$ as to sta'%ocused on eplanng t$e tec$nolog'. Eac$ o% t$s topc can ta)e ts o&n $ands-on lab andt$ere s enoug$ materal avalable on t$e (nternet. (ts $g$l' recommended to ma)e sure t$att$e code coped %rom t$s sample applcaton s updated to meet t$ose reurements.

    $.0 %uild t&e Te!'late (eb )''lication

    #$s secton &ll buld a template 5eb applcaton usng t$e :et0eans (7E.

    $.1(n :et0eans (7E, create a ne& 5eb applcaton b' selectng t$e *2le, *:e& ro8ect.

    $.2C$oose *Java 5eb as Categores and*5eb Applcaton as ro8ects.

    Clc) on *:etB.

    $.$pec%' t$e pro8ect name as*JavaEE6ampleApp and clc) on *:etB.

    $.*C$oose t$e pre-con%gured Glass2s$erver 1.! as t$e erver.

    #$e actual server name ma' d%%er n 'our case,

    as n t$s case, % 'ou $ave con%gured teternall'. Ensure t$at t$e Java EE 9erson selected s *Java EE 6 5eb and clc) on *2ns$.

    #$s generates a template 5eb pro8ect.

    #$ere s no web.xmln t$e WEB-INF%older as Java EE 6 ma)es t optonal n most o%

  • 5/26/2018 Java EE 6 Hands-on Lab

    5/47

    Java EE 6 Hands-on Lab

    t$e common cases.

    $.+4g$t-clc) on t$e pro8ect and select *4un. #$s

    &ll start t$e c$osen Glass2s$ server, deplo' t$e 5ebapplcaton on t$e server, opens t$e de%ault &ebbro&ser, and dspla's*$ttp=//local$ost=D3D3/JavaEE6ampleApp/nde.8sp .

    #$e de%ault page loo)s l)e as s$o&n.

    :ote t$at even t$oug$ t$e index.jsps not dspla'ed n t$e 4L &ndo&, t$s s t$ede%ault %le t$at s dspla'ed.

    A dspla' o% t$s page ensures t$at t$e pro8ect ssuccess%ull' created and Glass2s$ $as startedsuccess%ull' as &ell. #$e Glass2s$ server comesbundled &t$ t$e Java70 and s pre-con%gured n :et0eans to start t$e database server as&ell. #$s can be c$anged b' epandng t$e *ervers tree n t$e *ervces tab, rg$t-clc)ngon t$e c$osen server, selectng t$e propertes, and selectng/unselectng t$e c$ec)bo t$atsa's *tart 4egstered 7erb' erver.

    *.0 ,enerate J) Entities fro! t&e Database Table

    Java ersstence A( FJA s a standard A( t$at de%nes mappng bet&een database tablesand Java classes. #$ese OJOs can t$en be used to per%orm all t$e database operatonsusng Java ersstence uer' Language FJL &$c$ s a strng-based L-l)e s'nta or at'pe-sa%e Crtera A(. 0ot$ JL and Crtera A( operate on t$e Java model nstead o% t$edatabase tables.

    #$s secton &ll generate JA enttes %rom a sample database and custom+e t$em to bemore ntutve %or Java developers.

    *.1(n :et0eans, rg$t-clc) on t$epro8ect and select *:e&, *Ot$er...,*ersstence, *Entt' Classes %rom7atabase.... C$oose *8dbc/sample

    http://localhost:8080/JavaEE6SampleApp/index.jsphttp://localhost:8080/JavaEE6SampleApp/index.jsp
  • 5/26/2018 Java EE 6 Hands-on Lab

    6/47

    Java EE 6 Hands-on Lab

    as t$e 7ata ource %rom t$e drop do&n lst bo as s$o&n. #$s &ll s$o& all t$e tables %romt$s data source.

    *.2elect *C#OE4 table %rom t$e *Avalable #ables and clc) *AddB. :otce t$at t$e

    *7(CO:#ICO7E and *(C4OIA4>E# tables are automatcall' selected because o%t$e %oregn )e' re%erences and t$e selected *(nclude 4elated #ables c$ec)bo.

    Clc) on *:etB.

    *.$Enter t$e pac)age nameorg.glassfish.samples.entities

    as s$o&n.

    #$e mapped class names are s$o&n nt$e *Class :ame column and can bec$anged $ere, % needed.

    :otce t$e %ollo&ng ponts=

    #$e %rst c$ec) bo allo&s

    :et0eans to generate multple@NamedQueryannotatons on t$e JA entt'. #$ese annotatons provde pre-de%nedJL ueres t$at can be used allo&s to uer' t$e database.

    #$e second c$ec) bo ensures t$at t$e @XmlRootElementannotaton s generatedon t$e JA entt' class so t$at t can be converted to an ;L representaton easl' b'JA;0. #$s %eature s use%ul &$en t$e enttes are publs$ed as a 4E#%ul resource.

    #$e t$rd c$ec) bo generates t$e reured ersstence nt reured b' JA.

    Clc) on *2ns$ to complete t$e entt' generaton.

    (n :et0eans, epand *ource ac)ages, org.glassfish.samples.entities, anddouble-clc) Customer.java.

    :otce t$e %ollo&ng ponts n t$e generated code=

    #$e generated class-level @NamedQueryannotatons uses JL to de%ne several

    ueres. One o% t$e ueres s named *Customer.%ndAll &$c$ maps to t$e JL t$atretreves all ro&s %rom t$e database. #$ere are several *%nd0' ueres, one %or eac$%eld F&$c$ maps to a column n t$e table, t$at allo&s to uer' t$e data %or t$at

    6

  • 5/26/2018 Java EE 6 Hands-on Lab

    7/47

    Java EE 6 Hands-on Lab

    spec%c %eld. Addtonal ueres ma' be added $ere provdng a central locaton %or all'our uer'-related logc.

    #$e bean valdaton constrants are generated on eac$ %eld based upon t$e sc$ema

    de%nton. #$ese constrants are t$en used b' t$e valdator ncluded n t$e JA

    mplementaton be%ore an entt' s saved, updated, or removed %rom t$e database. #$e regular epresson-based constrant ma' be used to en%orce p$one or +pcode n a

    partcular %ormat.

    #$e zipand discountCode%elds are mar)ed &t$ t$e @JoinColumnannotaton

    creatng a 8on &t$ t$e approprate table.

    4.1 Walk-through the JPA Entities and Refactor to Simlif!

    #$s secton &ll custom+e t$e generated JA enttes to ma)e t$em more ntutve %or aJava developer.

    *.1.1Edt Customer.javaand c$ange t$e class structure to ntroduce an embeddableclass%or street, city, country, and zip%elds as t$ese are logcall' related enttes.

    4eplace t$e %ollo&ng code=

    @Size(max = 30)

    @Column(name = "ADDRESSLINE1") private String addressline1; @Size(max = 30) @Column(name = "ADDRESSLINE2") private String addressline2; @Size(max = 25) @Column(name = "CITY") private String city; @Size(max = 2) @Column(name = "STATE") private String state;

    and

    @JoinColumn(name = "ZIP", referencedColumnName = "ZIP_CODE") @ManyToOne(optional = false) private MicroMarket zip;

    &t$

  • 5/26/2018 Java EE 6 Hands-on Lab

    8/47

    Java EE 6 Hands-on Lab

    @javax.persistence.Embedded private Address address;

    se t$e 'ello& bulb n t$e le%t bar tocreate a ne& class n t$e currentpac)age as s$o&n=

    :otce t$e %ollo&ng ponts=

    #$e t&o bloc)s o% code above are not ad8acent.

    Cop'/pastng onl' t$e %elds &ll s$o& a red lne under some o% t$e met$ods n 'our

    entt' but &ll be %ed later.

    #$e @Embeddedannotaton ensures t$at t$s %elds value s an nstance o% an

    embeddable class.

    *.1.2C$ange Address.javaso t$at t s a publc class, annotate &t$ @Embeddablesuc$t$at t can be used as embeddable class, and also mplement t$e Serializablenter%ace.#$e updated class de%nton s s$o&n=

    @javax.persistence.Embeddablepublic class Address implements java.io.Serializable {

    *.1.$(n Address.java, paste t$e d%%erent %elds code replaced %rom Customer.javaand

    add getter/setters %or eac$ %eld. #$e met$ods can be easl' generated b' gong to t$e*ource, *(nsert Code..., selectng *Getter and etter..., selectng all t$e %elds, and t$enclc)ng on *Generate.

    2 all t$e mports b' rg$t-clc)ng n t$e edtor, selectng *2 (mports..., and ta)ng all t$ede%aults.

    *.1.*a)e t$e %ollo&ng c$anges n Customer.java=

    . 4emove t$e getter/setter %or t$e prevousl' removed %elds.

    . Add a ne& getter/setter %or *address %eld as=

    public Address getAddress() { return address; }public void setAddress(Address address) { this.address = address; }

    . C$ange t$e d%%erent @NamedQueryto re%lect t$e nested structure %or Addressb'edtng t$e ueres dent%ed b' Customer.findByAddressline1,

    D

  • 5/26/2018 Java EE 6 Hands-on Lab

    9/47

    Java EE 6 Hands-on Lab

    Customer.findByAddressline2, Customer.findByCity, andCustomer.findByStatesuc$ t$at c.addressline1, c.addressline2, c.city,and c.states replaced &t$ c.address.addressline1,c.address.addressline2, c.address.city, and c.address.staterespectvel'.

    Here s one o% t$e updated uer'=

    @NamedQuery(name = "Customer.findByCity", query = "SELECT c FROM Customer cWHERE c.address.city = :city")

    i-. C$ange t$e mplementaton o% t$e toStringmet$od as s$o&n belo&=

    @Overridepublic String toString() { return name + "[" + customerId + "]";

    }

    #$s &ll ensure t$at t$e customers name and unue dent%er are prnted as t$ede%ault strng representaton.

    +.0 uer t&e Database fro! a "ervlet

    (n Java EE 6, ervlet can easl' be de%ned usng a OJO, &t$ a sngle annotaton, and

    optonal web.xmln most o% t$e common cases.

    #$s secton &ll create a ervlet and nvo)e t$e @NamedQueryto uer' t$e database.

    +.14g$t-clc) on t$e pro8ect, select *:e&, *ervlet.... Enter t$e class name as *#estervlet,pac)age as org.glassfish.samples, and clc) on *2ns$.

    Epand *5eb ages, *5E0-(:2 and notce t$at no web.xmls generated %ordescrbng t$s ervlet as all t$e n%ormaton s captured n t$e @WebServletannotaton.

    @WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})public class TestServlet extends HttpServlet {

    +.2(n8ect EntityManagerFactoryn ervlet b' addng t$e %ollo&ng code rg$t a%ter t$eclass declaraton=

    K

  • 5/26/2018 Java EE 6 Hands-on Lab

    10/47

    Java EE 6 Hands-on Lab

    @PersistenceUnit EntityManagerFactory emf;

    4esolve t$e mports b' rg$t-clc)ng on t$e 'ello& bulb.

    +.$n-comment t$e code n t$e tr' bloc) o% t$e processRequestmet$od b' removng t$e%rst and last t$e lne n t$e tr' bloc). Add t$e code to use t$e n8ectedEntityManagerFactoryto uer' t$e database usng a pre-generated @NamedQuerytoretreve all t$e customers.

    #$e updated tr' bloc) loo)s l)e=

    try { out.println(""); out.println(""); out.println("Servlet TestServlet");

    out.println(""); out.println(""); out.println("Servlet TestServlet at " +

    request.getContextPath () + ""); List result = (List)emf. createEntityManager(). createNamedQuery("Customer.findAll"). getResultList(); for (Customer c : result) out.println(c + "
    "); out.println(""); out.println(""); } finally {

    nce t$e ervlets are re-entrant and EntityManagers not t$read sa%e, t needs to beobtaned %rom an EntityManagerFactorydurng eac$ met$od nvocaton. #$s s resolved&$en t$e database spec%c code s moved to an EJ0 later.

    :otce t$at no transactons are started orcommtted be%ore/a%ter t$e database

    operaton as t$s s a read-onl' operaton anddoes not $ave t$e demands o% a real-l%eapplcaton. An eplct transacton $as to becreated and commtted For rollbac)ed % et$ercreate, update, or delete operatons are

    per%ormed. (n addton, JA" also provdessupport %or optmstc and pessmstc loc)ng b'means o% spec%ed loc)ng modes.

    +.*4g$t-clc) n t$e edtor pane, select *4un2le, c$oose t$e de%aults, and clc) on O>.

    !3

  • 5/26/2018 Java EE 6 Hands-on Lab

    11/47

    Java EE 6 Hands-on Lab

    #$s dspla's *$ttp=//local$ost=D3D3/JavaEE6ampleApp/#estervlet page n t$e bro&serand loo)s l)e as s$o&n.

    6.0 )ctive /ede'lo to reserve "essions

    Glass2s$ provdes support %or preservng sesson state across redeplo'ments. #$s %eature scalled asActive Redeployand &or)s %or H## sessons, state%ul EJ0s, and persstentl'created EJ0 tmers.

    #$s secton &ll s$o& $o& Actve 4edeplo' %or H## sessons, toget$er &t$ :et0eansauto-deplo', boosts productvt' %or Java EE 6 applcaton developers.

    6.1(n TestServlet.java, add t$e %ollo&ng code be%ore t$e database access code=

    int count; if (request.getSession().getAttribute("count") == null) { count = 0; } else { count = (Integer) request.getSession().getAttribute("count"); } request.getSession().setAttribute("count", ++count); out.println("Timestamp: " + new Date() + "
    "); out.println("Times: " + request.getSession().getAttribute("count") + "");

    2 t$e mports b' ta)ng t$e de%aults.

    #$s code stores a sessonattrbute dent%'ng t$enumber o% tmes a page $asbeen accessed.

    4e%res$ t$e page*$ttp=//local$ost=D3D3/JavaEE6ampleApp/#estervletn t$e bro&ser to see t$e

    output as s$o&n.

    #$e *#mestamp and *Access count s dspla'ed on t$e page.

    #$e output %rom t$e ervlet ma' loo) slg$tl' d%%erent based upon &$ere 'ou cop'/pastedt$e code.

    !!

    http://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlet
  • 5/26/2018 Java EE 6 Hands-on Lab

    12/47

    Java EE 6 Hands-on Lab

    6.2Edt Customer.java, c$ange t$e mplementaton o% t$e toStringmet$od to=

    return name + " (" + customerId + ")";

    :otce, * * are replaced &t$ * F*. ave t$e %le.

    #$e :et0eans (7E auto-deplo's a Java EE 6pro8ect &t$ ever' %le save. #$s can becon%gured n *ro8ect ropertes, *4un, and b'selectng/unselectng t$e c$ec)bo *7eplo' onave as s$o&n.

    #$e updated output loo)s l)e as s$o&n.

    :otce, t$at even t$oug$ t$e output %rom t$e toStrings correctl' updated, ndcatngt$e app &as redeplo'ed success%ull', t$e sesson access count &as ncremented b' one.

    #$s s$o&s t$at t$e sesson attrbutes &ere preserved across t$e redeplo'ment.

    #$s boosts developers productvt' because H##sesson, &$c$ s &$ere t'pcall' 'our lognn%ormaton mg$t be stored, s not nvaldated % 'ourapplcaton s redeplo'ed. #$s s an optonal %eatureand can be dsabled b' ve&ng t$e propertes o% t$eGlass2s$ server n t$e *ervces tab o% :et0eans

    and unselectng *reserve essons Across4edeplo'ment.

    !"

  • 5/26/2018 Java EE 6 Hands-on Lab

    13/47

    Java EE 6 Hands-on Lab

    .0 uer t&e Database usin EJ% and /efactor t&e "ervlet

    Java EE 6 provdes a smpl%ed de%nton and pac)agng %or EJ0s. An' OJO can beconverted nto an EJ0 b' addng a sngle annotaton F@Stateless, @Stateful, or

    @Singleton. :o specal pac)agng s reured %or EJ0s as t$e' can be pac)aged n a 5A4%le n t$e WEB-INF/classesdrector'.

    #$s secton &ll create an EJ0 to uer' t$e database.

    .1Create a ne& stateless EJ0. 4g$t-clc) on*org.glass%s$.samples pac)age, select *:e&, *esson 0ean...,spec%' t$e EJ0 :ame as *Customeresson0ean, ta)e all t$ede%aults, and clc) on *2ns$ as s$o&n.

    #$s &ll create a stateless EJ0. :otce t$e generated EJ0 doesnot mplements an nter%ace. #$s s a ne& %eature o% EJ0 1.!.

    .2EJ0s are not re-entrant and so &e can n8ect an nstance o%EntityManager, as opposed to EntityManagerFactoryn t$eervlet, as s$o&n=

    @PersistenceContextEntityManager em;

    a)e sure to resolve t$e mports b' rg$t-clc)ng on t$e edtor pane and selectng *2(mports.

    .$Add t$e %ollo&ng met$od n t$e EJ0=

    public List getCustomers() { return (List)em.createNamedQuery("Customer.findAll").getResultList();}

    #$e mplementaton $ere s smlar to t$e code used n t$e ervlet earler.

    2 t$e mports.

    #$ats all t ta)es to create an EJ0 M no deplo'ment descrptors and no specal pac)agng. (nt$s case t$e EJ0 s pac)aged n a 5A4 %le.

    !1

  • 5/26/2018 Java EE 6 Hands-on Lab

    14/47

    Java EE 6 Hands-on Lab

    .*#$e database access code n t$e ervlet can no& be removed and all o% t$at %unctonalt'can be delegated to t$s EJ0. #$s can be done b' replacng t$e %ollo&ng code %rom t$eervlet=

    @PersistenceUnit EntityManagerFactory emf;

    &t$

    @EJB CustomerSessionBean bean;

    And replacng t$e %ollo&ng code=

    List result = (List)emf. createEntityManager(). createNamedQuery("Customer.findAll"). getResultList();

    &t$

    List result = bean.getCustomers();

    :otce $o& an EJ0 s easl' n8ected usng t$e @EJBannotaton and s t$en used to nvo)e t$ebusness met$od.

    4e%res$ng*$ttp=//local$ost=D3D3/JavaEE6ampleApp/#estervlet dspla's t$e output as s$o&n.

    #$s s almost t$e same output as s$o&nearler, and t$ats t$e &$ole pontN EJ0sare better suted %or database access as allmet$ods are mplctl' transactonal. #$s&ll be more apparent &$en &e add codeto nsert values n t$e database table.sng an EJ0, nstead o% ervlet, &ll not reure to start and commt a transacton eplctl'.

    #$e onl' d%%erence %rom t$e prevous output s t$e updated tmestamp and t$e access count$as ncreased b' !.

    .0 )dd 3alues to t&e Database usin EJ%4 use %ean 3alidationConstraints

    0ean 9aldaton s a ne& spec%caton added to t$e Java EE 6 plat%orm. #$s spec%caton

    !

    http://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlet
  • 5/26/2018 Java EE 6 Hands-on Lab

    15/47

    Java EE 6 Hands-on Lab

    de%nes an etensble valdaton constrants mec$ansm, &t$ a pre-de%ned set o% constrants,t$at can be spec%ed on %eld, met$od, t'pe, or annotatons. (t also de%nes a valdaton %aclt'%or t$e Java applcaton developer.

    #$e constrants can be spec%ed on a JA entt' and t$e valdaton %aclt' ensure t$ese are

    met durng t$e pre-persst, pre-update, and pre-remove l%ec'cle events. #$ese constrantscan also be used on *bac)ng beans %or %orms dspla'ed b' J2. #$s ensures t$at t$e dataentered n t$e %orm meets t$e valdaton crtera.

    #$s secton &ll eplan $o& EJ0 can be used to add values to t$e database and 0ean9aldaton constrants can be used to automatcall' valdate t$e data.

    .1Add a ne& met$od to t$e EJ0 as=

    public void addCustomer(Integer customerId,String name,Address address,String phone,String fax,String email,Integer creditLimit,DiscountCode discountCode) {

    Customer c = new Customer(customerId); c.setName(name); c.setAddress(address); c.setPhone(phone); c.setFax(fax); c.setCreditLimit(creditLimit); c.setDiscountCode(discountCode); em.persist(c); }

    #$s met$od ta)es a %e& parameters and adds a ne& customer to t$e database b' callng t$epersistmet$od on t$e EntityManager.

    .2Add t$e %ollo&ng code to t$e ervlet=

    String id = request.getParameter("add");if (id != null) { Address address = new Address(); address.setAddressline1("4220, Network Circle"); address.setCity("Santa Clara"); address.setState("CA"); MicroMarket zip = new MicroMarket(); zip.setZipCode("95051"); address.setZip(zip); bean.addCustomer(Integer.parseInt(id), "FLL Enterprises",

    address,

    !

  • 5/26/2018 Java EE 6 Hands-on Lab

    16/47

    Java EE 6 Hands-on Lab

    "1234","5678","[email protected]",1000,new DiscountCode('H'));

    out.println("Customer with '" + Integer.parseInt(id) + "' id

    added.");}

    #$s code %ragment loo)s %or t$e *add parameter spec%ed as part o% t$e 4L and t$ennvo)es t$e EJ0s met$od to add a ne& customer to t$e database. #$e customer dent%er sobtaned as a value o% t$e parameter and all ot$er values are de%aulted.

    .$Access*$ttp=//local$ost=D3D3/JavaEE6ampleApp/#estervletaddP n t$e bro&ser and t$s&ll add a ne& customer F&t$ d * n t$s

    case to t$e database and dspla's t$epage as s$o&n.

    :otce t$e ne&l' added customer s no&s$o&n n t$e lst.

    #$e customer dent%er s spec%ed aspart o% t$e 4L so ts mportant to pc)

    a number t$at does not alread' est n t$edatabase.

    .*One o% t$e bean valdaton constrantsmentoned on Customer.javas %or t$ep$one number Fdent%ed b' t$e %eldphone to be a mamum o% !" c$aracters. Lets update t$e constrant suc$ t$at t reures atleast < c$aracters to be spec%ed as &ell. #$s can be done b' c$angng t$e estngconstrant %rom=

    @Size(max = 12)

    to

    @Size(min = 7, max = 12)

    ave t$e %le and t$e pro8ect automatcall'gets re-deplo'ed.

    !6

    http://localhost:8080/JavaEE6SampleApp/TestServlet?add=4http://localhost:8080/JavaEE6SampleApp/TestServlet?add=4http://localhost:8080/JavaEE6SampleApp/TestServlet?add=4http://localhost:8080/JavaEE6SampleApp/TestServlet?add=4
  • 5/26/2018 Java EE 6 Hands-on Lab

    17/47

    Java EE 6 Hands-on Lab

    .+Access t$e 4L *$ttp=//local$ost=D3D3/JavaEE6ampleApp/#estervletaddP n abro&ser and t$s tres to add a ne& customer to t$e database and s$o&s t$e output ass$o&n.

    :otce t$e lst o% customers s not s$o&n. (nstead t$e Glass2s$ output log s$o&s t$e

    %ollo&ng message=

    Caused by: javax.validation.ConstraintViolationException: Bean Validationconstraint(s) violated while executing Automatic Bean Validation on callbackevent:'prePersist'. Please refer to embedded ConstraintViolations for details.

    #$s error message comes because t$e p$one number s spec%ed as a -dgt number n t$eervlet and so does not meet t$e valdaton crtera. #$s can be %ed b' c$angng t$e p$onenumber to spec%' < dgts.

    .6Edt TestServlet.java, c$ange t$ep$one number %rom *!"1 to *!"16

  • 5/26/2018 Java EE 6 Hands-on Lab

    18/47

    Java EE 6 Hands-on Lab

    #$e JA" spec%caton de%nes a canoncal metamodel. :et0eans uses *EclpseLn)Canoncal etamodel Generator to generate t$ese metamodel classes &$en t$e pro8ect sbult. #$s s pre-con%gured n *ro8ect ropertes, *Lbrares, *rocessor as s$o&n.

    Here s $o& t$e generated Address_.javaclass loo)s l)e=

    package org.glassfish.samples.entities;

    import javax.annotation.Generated;import javax.persistence.metamodel.SingularAttribute;import javax.persistence.metamodel.StaticMetamodel;import org.glassfish.samples.entities.MicroMarket;

    @Generated(value="EclipseLink-2.2.0.v20110202-r8913", date="2011-11-07T16:13:45")@StaticMetamodel(Address.class)public class Address_ {

    public static volatile SingularAttribute addressline2;

    public static volatile SingularAttribute zip; public static volatile SingularAttribute addressline1; public static volatile SingularAttribute state; public static volatile SingularAttribute city;

    }

    #$s class provdes t$e t'pe and cardnalt' o% eac$ %eld n t$e Addressentt'.

    5.2Add t$e %ollo&ng code to CustomerSessionBean.java=

    public List getCustomers2() { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(Customer.class);

    // FROM clause Root root = criteria.from(Customer.class);

    // SELECT clause criteria.select(root);

    !D

  • 5/26/2018 Java EE 6 Hands-on Lab

    19/47

    Java EE 6 Hands-on Lab

    // No WHERE clause

    // FIRE query TypedQuery query = em.createQuery(criteria);

    // PRINT result

    return query.getResultList(); }

    #$s met$od returns t$e lst o% all customers %rom t$e database, 8ust l)e getCustomersmet$od earler, but uses t'pe-sa%e Crtera A( to uer' t$e database.

    #$e generated metamodel &ll be used later.

    :ote t$at all t$e n%ormaton s spec%ed &t$out an' strng-based dent%ers.

    2 t$e mports b' ta)ng all t$e de%aults.

    5.$(n *#estervlet.8ava, replace t$e code=

    List result = bean.getCustomers();

    &t$

    List result = bean.getCustomers2();

    :otce t$e ne& EJ0 %uncton s no& nvo)ed.

    2 t$e mports.

    5.*4e%res$ t$e page*$ttp=//local$ost=D3D3/JavaEE6ampleApp/#estervlet n bro&ser to see an output l)e=

    #$s con%rms t$at t$ere s no c$ange n t$eoutput, as epected.

    !K

    http://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlethttp://localhost:8080/JavaEE6SampleApp/TestServlet
  • 5/26/2018 Java EE 6 Hands-on Lab

    20/47

    Java EE 6 Hands-on Lab

    10.0 Cac&in usin "inleton EJ% and 7"c&edule to re-fetc&Data

    #$e EJ0 1.! spec%caton ntroduces @Singletonannotaton t$at creates a sngle nstanceo% an EJ0 per-applcaton and per-J9. 0' de%ault, all met$ods are t$read-sa%e andtransactonal. #$e spec%catons also smpl%es $o& to sc$edule callbac) met$ods usngcalendar-based epressons. #$ese met$ods can be nvo)ed at a spec%ed tme, a%ter aspec%ed elapsed duraton, or at recurrng ntervals.

    #$s secton adds a sngleton EJ0 t$at can be used to pre-%etc$ data %rom t$e database atrecurrng ntervals.

    10.14g$t-clc) on *org.glass%s$.samples pac)age, t'pe t$e name

    as *Cac$engleton0ean, and t'pe as *ngleton as s$o&n.

    And clc) on O>.

    10.2Add t$e %ollo&ng class-level annotaton=

    @javax.ejb.Startup

    #$s &ll ensure t$at t$s sngleton bean s loaded eagerl' durng t$e applcaton startup.

    10.$Add t$e %ollo&ng code to t$e generated class=

    @EJB CustomerSessionBean bean; List customers;

    public List getCustomers() { return customers; }

    @Schedule(hour="*", minute="*", second="*/30") public void preFetchCustomers() { System.out.println(new Date() + " Fetching customers");

    customers = bean.getCustomers(); }

    2 t$e mports.

    #$s code s usng prevousl' created CustomerSessionBeanto get t$e lst o% customers.#$s met$od $as a @Scheduleannotaton t$at ta)es cron-l)e s'nta to spec%' t$e recurrng

    "3

  • 5/26/2018 Java EE 6 Hands-on Lab

    21/47

    Java EE 6 Hands-on Lab

    nterval at &$c$ t$e met$od needs to be nvo)ed.

    #$e Glass2s$ server log &ll s$o& messages l)e=

    INFO: Tue Nov 08 00:06:00 CET 2011 Fetching customers

    INFO: Tue Nov 08 00:06:30 CET 2011 Fetching customersINFO: Tue Nov 08 00:07:00 CET 2011 Fetching customersINFO: Tue Nov 08 00:07:30 CET 2011 Fetching customersINFO: Tue Nov 08 00:08:00 CET 2011 Fetching customers

    #$e log messages s$o& t$at customer cac$e s updated ever' 13 seconds, as de%ned b'@Schedule.

    #$e applcaton can no& use t$s sngleton bean, nstead o% CustomerSessionBean, to gett$e lst o% customers suc$ as=

    @EJB CacheSingletonBean bean;

    . . .

    bean.preFetchCustomers();

    :ote, bean.getCustomers()cannot be nvo)ed as t ma' return null% t$e tmer event$as not occurred 'et at least once.

    Qou ma' consder commentng @Scheduleannotaton to avod %loodng t$e server log &t$an output %rom t$e preFetchCustomersmet$od.

    11.0 3C usin J"8298acelets-based vie:

    Javaerver 2aces " allo&s 2acelets to be used as t$e ve& templates. #$s $as $uge bene%tsas 2acelets are created usng onl' ;H#L and C and rest o% t$e busness logc scontaned n t$e bac)ng beans. #$s ensures t$at 9C arc$tecture recommended b' J2can be easl' ac$eved. #$e model s provded b' t$e JA entt', t$e ve& s served b' J2",and controller s an EJ0. Even t$oug$ Js can stll be used as ve& templates but 2aceletsare $g$l' recommended &t$ J2".

    #$e Contets and 7ependenc' (n8ecton FC7( s a ne& spec%caton n t$e Java EE 6plat%orm and brdges t$e gap bet&een t$e transactonal and t$e 5eb ter b' allo&ng EJ0s tobe used as t$e *bac)ng beans o% t$e J2 pages. #$s elmnates t$e need %or an' *gluecode, suc$ as JSF managed beans, and t$ere b' %urt$er smpl%'ng t$e Java EE plat%orm.

    #$s secton adds J2 support to t$e applcaton and dspla' t$e lst o% customers n a

    "!

  • 5/26/2018 Java EE 6 Hands-on Lab

    22/47

    Java EE 6 Hands-on Lab

    2acelets-based ve&. #$e EJ0 met$ods &ll be nvo)ed n t$e Epresson Language toaccess t$e database.

    11.1#$e C7( spec%caton reure beans.xmln t$e 5E0-(:2 drector' to enable n8ecton o%

    beans &t$n a 5A4 %le. #$s &ll allo& to use t$e EJ0 n an Epresson Language FEL, suc$as .xhtmlpages t$at &ll becreated later.

    4g$t-clc) on t$e pro8ect, sa'*:e&, *Ot$er..., c$oose *Contets

    and 7ependenc' (n8ecton,select *beans.ml FC7(

    Con%guraton 2le as s$o&n.

    Clc) on *:etB, ta)e all t$e de%aults as

    s$o&n.

    Clc) on *2ns$.

    #$s generates an empt' beans.xml%le n t$e WEB-INF%older and ensurest$at all OJOs n t$e 5A4 %le areavalable %or n8ecton.

    11.2Add @javax.inject.NamedC7( ual%er on t$e CustomerSessionBeanclass. #$s

    s a pre-de%ned C7( ual%er Feplaned later and ensures t$at t$e EJ0 can no& be n8ectedn an epresson language.

    11.$4g$t-clc) on t$e pro8ect, select *ropertes,*2rame&or)s, *Add..., and select *Javaerver 2acesas s$o&n. Clc) on *O>, ta)e t$e de%ault con%guraton,and clc) on *O> agan.

    5t$ J2 ".3 mplementaton n Glass2s$, % an' J2-

    spec%c annotatons s used n t$e applcaton t$en t$e%rame&or) s automatcall' regstered b' t$e underl'ng5eb contaner. 0ut snce our applcaton s not usng an' suc$ annotaton so &e $ave toeplctl' enable t.

    Addng t$e %rame&or) n t$s case &ll generate a web.xml&$c$ regsters t$e *2aceervletusng t$e */%aces 4L pattern. (t also generates index.xhtmlpage &$c$ can be ver%ed

    ""

  • 5/26/2018 Java EE 6 Hands-on Lab

    23/47

    Java EE 6 Hands-on Lab

    b' ve&ng *$ttp=//local$ost=D3D3/JavaEE6ampleApp/%aces/nde.$tml &t$ t$e output ass$o&n.

    11.*J2" allo&s to create ;H#L/C-based templates t$at can be used %or provdng aconsstent loo)-and-%eel %or d%%erentpages o% 'our &ebste. Lets create atemplate %rst and t$en use t %or our&eb page.

    4g$t-clc) on t$e pro8ect, select

    *:e&, *Ot$er, *Javaerver 2aces,*2acelets #emplate..., c$ange t$ename to *template, clc) on*0ro&se..., select t$e *5E0-(:2%older, and select t$e template ass$o&n. Clc) on *2ns$.

    :otce t$e %ollo&ng ponts=

    #$s generates WEB-INF/template.xhtmland t&o st'les$eets n t$e

    resources/css%older. :et0eans contans a pre-de%ned set o% templates andaddtonal ones can be created usng ;H#L/C. #$e template.xhtmlpage contans t$ree s &t$ named *top,

    *content, and *bottom. #$ese are place$olders %or addng content to provde aconsstent loo)-and-%eel.

    (ts a recommended practce to )eep t$e template pages n t$e WEB-INF%older to

    restrct t$er vsblt' to t$e &eb applcaton.

    11.+(n t$e generated template.xhtml, replace t$e tet *#op Fnsde &t$=

    Java EE 6 Sample App

    and replace t$e tet *0ottom &t$ Fnsde &t$=

    Powered by GlassFish!

    "1

    http://localhost:8080/JavaEE6SampleApp/faces/index.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/index.xhtml
  • 5/26/2018 Java EE 6 Hands-on Lab

    24/47

    Java EE 6 Hands-on Lab

    #$e *top and *bottom s &ll be used n ot$er pages n our applcaton to provde aconsstent loo)-and-%eel %or t$e &eb applcaton. #$e *content &ll be overrdden not$er pages to dspla' t$e busness components.

    11.6:o& lets re-generate index.xhtmlto use t$s template. #$s page, called as *clentpage, &ll use t$e $eader and t$e %ooter %rom t$e template page and overrde t$e reureds usng . #$e rest o% t$e secton s n$erted %rom t$e template page.

    2rst, delete index.xhtmlb' rg$t-clc)ng and selectng *7elete.

    4g$t-clc) on *5eb ages, select *:e&, *Ot$er, *Javaerver2aces n Categores and *2acelets #emplate Clent... n 2le #'pes.Clc) on *:etB.Enter t$e %le name as *nde, c$oose t$e *0ro&se... button net to

    *#emplate= tet bo, select *template.$tml as s$o&n, and clc) on*elect 2le.

    Clc) on *2ns$.

    :otce t$e %ollo&ng ponts=

    #$e generated page, index.xhtml, $as ndcatng t$at t$s page s usng t$e template page createdearler.

    (t $as t$ree elements, nstead o% n t$e template, &t$t$e eact same name as n t$e template. #$s allo&s spec%c sectons o% t$e templatepage to be overrdden. #$e sectons t$at are not overrdden are pc)ed up %rom t$etemplate.

    11.4e%res$ *$ttp=//local$ost=D3D3/JavaEE6ampleApp/%aces/nde.$tml to see t$e outputas=

    #$e output dspla's t$ree sectons %romt$e index.xhtml%le as generated b'

    t$e :et0eans &+ard.

    11.(n index.xhtml, delete t$eelement &t$ name *topand *bottom as t$ese sectons arealread' de%ned n t$e template.

    "

    http://localhost:8080/JavaEE6SampleApp/faces/index.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/index.xhtml
  • 5/26/2018 Java EE 6 Hands-on Lab

    25/47

    Java EE 6 Hands-on Lab

    11.54eplace t$e tet *content Fnsde &t$=

    Customer Name #{c.name} Customer ID #{c.customerId}

    #$s J2 %ragment n8ects t$e EJ0 nto t$e epresson language, nvo)es ts getCustomersmet$od, terates t$roug$ all t$e values, and t$en dspla's t$e name and d o% eac$ customer.(t also dspla's table and column $eaders.

    #$e fand hpre% used n t$e %ragment snot re%errng to an' namespace. #$sneeds to be %ed b' rg$t-clc)ng on t$e'ello& bulb as s$o&n. elect t$eproposed %. 4epeat t$s % %or fpre% as &ell.

    11.104e%res$ng t$e page*$ttp=//local$ost=D3D3/JavaEE6ampleApp/%aces/nde.$tml dspla's t$e resultas s$o&n.

    As 'ou can see, t$e *top and*bottom sectons are beng

    n$erted %rom t$e template and t$e*content secton s pc)ed up %romindex.xhtml.

    Addtonal pages can be added to t$s&eb applcaton usng t$e sametemplate and t$us provdng consstentloo)-and-%eel.

    "

    http://localhost:8080/JavaEE6SampleApp/faces/index.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/index.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/index.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/index.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/index.xhtml
  • 5/26/2018 Java EE 6 Hands-on Lab

    26/47

    Java EE 6 Hands-on Lab

    12.0 D/; usin J"82 Co!'osite Co!'onent

    #$e J2" spec%caton de%nes a composite componentas a component t$at conssts o% oneor more J2 components de%ned n a 2acelet mar)up %le t$at resdes nsde a resource

    lbrar'. #$e composte component s de%ned n t$e defining pageand used n t$e using page.#$e de%nng page de%nes t$e metadata For parameters usng andmplementaton usng &$ere ccs t$e pre% %or t$ehttp://java.sun.com/jsf/compositenamespace.

    #$s secton &ll convert a 2acelets mar)up %ragment %rom index.xhtmlnto acomposte component.

    12.1(n index.xhtml, select t$e %ragment as s$o&n.

    Clc) on t$e 'ello& bulb as s$o&n and select t$e $nt.

    12.2#a)e t$e de%aults as s$o&n.

    and clc) on *2ns$.

    "6

  • 5/26/2018 Java EE 6 Hands-on Lab

    27/47

    Java EE 6 Hands-on Lab

    #$e updated index.xhtml, t$e usng page, loo)s l)e=

    (t $as a ne& namespace http://java.sun.com/jsf/composite/ezcomp&t$ apre% ez. #$e namespace s t$e standard namespace de%ned b'

    t$e spec%caton su%%ed &t$ ezcomp. #$s ezcomps a ne& drector'created n t$e standard resourcesdrector' de%ned b' t$e J2"spec%caton. #$e tag name %or t$e ne& composte component s t$esame as t$e de%nng page %le name. #$e updated drector' structureloo)s l)e=

    #$e entre %ragment nsde s replaced &t$. #$s allo&s a collecton o% J2 components to be etractednto a composte component %ollo&ng t$e 7ont-4epeat-Qoursel% F74Q prncple and enablesto use nstead o% repeatng t$at entre code %ragment. (t also allo&s developers toaut$or ne& components &t$out an' Java code or ;L con%guraton.

    #$e de%nng page out.xhtmlloo)s l)e=

    Customer Name #{c.name} Customer ID #{c.customerId}

    "

  • 5/26/2018 Java EE 6 Hands-on Lab

    28/47

    Java EE 6 Hands-on Lab

    #$e de%nes metadata t$at descrbe t$e c$aracterstcs o% t$s component,suc$ as supported attrbutes, %acets, and even attac$ ponts %or event lsteners.contans t$e mar)up substtuted %or t$e composte component,%ragment %rom index.xhtmln t$s case.

    #$e s generated n t$e page but s empt' and ma' be made opton n asubseuent release o% t$e J2 spec%caton.

    4e%res$ng *$ttp=//local$ost=D3D3/JavaEE6ampleApp/%aces/nde.$tml s$o&s t$e sameresult as be%ore.

    1$.0 Declarative )

  • 5/26/2018 Java EE 6 Hands-on Lab

    29/47

    Java EE 6 Hands-on Lab

    #{c}

    #$s code dspla's an nput tet bo and bnds t to t$e *value propert' o% *Customer:amebean Fto be de%ned later. #$e tag attac$es A8a be$avor to t$e nput tet bo.#$e meanng o% eac$ attrbute s eplaned n t$e table belo&=

    Attrbute urpose

    event Event o% t$e appled component %or &$c$ t$e A8a acton s %red, onkeyupnt$s case.

    render Lst o% components t$at &ll be rendered a%ter t$e A8a acton s complete. #$senables *partal page renderng.

    listener et$od lstenng %or t$e A8a event to be %red. #$s met$od must ta)eAjaxBehaviorEventas t$e onl' parameter and return a void.

    #$e s t$e place$older %or dspla'ng t$e lst o% customers.

    :ote t$at t$e partal ve& s stll rendered on t$e server. #$e updated porton s sent to t$ebro&ser &$ere t$e 7O s updated.

    1$.*Add a ne& Java class b' rg$t-clc)ng on t$e pro8ect, selectng *:e&, *Java Class...,gve t$e name as *Customer:ame. C$ange t$e code to=

    @Modelpublic class CustomerName { private String value;

    public String getValue() { return value; }

    public void setValue(String value) { this.value = value; }

    }

    #$e @Modelannotaton s a C7( stereot'pe t$at s a smpl%ed &a' o% sa'ng t$at t$e bean sbot$ @Namedand @RequestScoped. A $and%ul o% stereot'pes are alread' pre-de%ned n t$eC7( spec%caton and ne& ones can be easl' de%ned.

    "K

  • 5/26/2018 Java EE 6 Hands-on Lab

    30/47

    Java EE 6 Hands-on Lab

    1$.+Add t$e %ollo&ng met$od to CustomerSessionBean.java=

    public void matchCustomers(AjaxBehaviorEvent evt) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(Customer.class); // FROM clause

    Root root = criteria.from(Customer.class);

    // SELECT clause criteria.select(root);

    // WHERE clause Predicate condition = builder.like(root.get(Customer_.name), "%" + name.getValue() + "%"); criteria.where(condition);

    // FIRE query TypedQuery query = em.createQuery(criteria);

    // PRINT result cust = query.getResultList();

    return;

    }

    #$s met$od s smlar to getCustomers2added earler. #$e t&o d%%erences are=

    #$e met$od ta)es AjaxBehaviorEventas t$e parameter as t$s s reurement %or

    t$e listenerattrbute o% .

    #$e Crtera uer' spec%es a 5HE4E clause usng t$e JA" metamodel t$at &as

    generated earler. #$e clause narro&s do&n t$e searc$ results &$ere t$e customers

    name conssts o% t$e strng mentoned n t$e nput tet bo.

    2 t$e mports. a)e sure javax.persistence.criteria.Predicateclass smported, t$s s not t$e de%ault.

    1$.6(n8ect t$e customer name as=

    @Inject CustomerName name;

    1$.Add a ne& %eld as=

    private List cust;

    #$s %eld s used to return t$e partal lst o% customers meetng t$e crtera. Add a getter %or tas=

    13

  • 5/26/2018 Java EE 6 Hands-on Lab

    31/47

    Java EE 6 Hands-on Lab

    public List getCust() { return cust; }

    1$.ave all t$e %les and open *$ttp=//local$ost=D3D3/JavaEE6ampleApp/%aces/lst.$tml nt$e bro&ser. #$e de%ault output loo)s ver' %amlar as s$o&n.

    #$s s because no crtera s spec%ed n t$e tet and so t$e complete lst s s$o&n.

    :o&, % 'ou t'pe *a n t$e tet bo t$en t$e lst o% customers s narro&ed do&n to t$e namest$at contan *a as s$o&n. ome ot$er sample results are s$o&n as &ell.

    1!

    http://localhost:8080/JavaEE6SampleApp/faces/list.xhtmlhttp://localhost:8080/JavaEE6SampleApp/faces/list.xhtml
  • 5/26/2018 Java EE 6 Hands-on Lab

    32/47

    Java EE 6 Hands-on Lab

    :otce, all o% t$s s onl' re%res$ng t$e and t$ere b' s$o&ng *partal pagere%res$ or *partal page renderng.

    1*.0 ublis& EJ% as a /E"Tful /esource usin J)=-/"

    #$e JA;-4 !.! spec%caton de%nes a standard A( to provde support %or 4E#%ul 5ebservces n t$e Java plat%orm. Just l)e ot$er Java EE 6 tec$nologes, an' OJO can be easl'converted nto a 4E#%ul resource b' addng t$e @Pathannotaton. JA;-4 !.! allo&s anEJ0 to be publs$ed as a 4E#%ul entt'.

    #$s secton publs$es an EJ0 as a 4E#%ul resource. A ne& met$od s added to t$e EJ0

    &$c$ &ll be nvo)ed &$en t$e 4E#%ul resource s accessed usng t$e H## GE#met$od.

    1*.1(n CustomerSessionBean.java, add a class-level @Pathannotaton to publs$ EJ0as a 4E#%ul entt'. #$e updated code loo)s l)e=

    @Stateless@LocalBean@Named@Path("/customers")public class CustomerSessionBean {

    #$e ne& annotaton s $g$lg$ted n bold. #$e%ollo&ng &ndo& pops up as soon as 'ou save t$s%le=

    #$e *4E# 4esources at$ s t$e base 4( %orservcng all reuests %or 4E#%ul resources n t$s&eb applcaton. #$e de%ault value o% */resources salread' used b' t$e .xhtmltemplates and Cused b' J2. o c$ange t$e value to */rest%ul andclc) on *O>.

    :otce t$at a ne& class t$at etendsjavax.ws.rs.core.Applications

    generated n t$eorg.netbeans.rest.application.configpac)age. #$s class regsters t$e base 4(%or all t$e 4E#%ul resources provded b' @Path. #$e updated base 4( s *rest%ul as can beseen n t$e generated class.

    1"

  • 5/26/2018 Java EE 6 Hands-on Lab

    33/47

    Java EE 6 Hands-on Lab

    1*.2Add t$e %ollo&ng met$od to CustomerSessionBean.java=

    @GET

    @Path("{id}")@Produces("application/xml")public Customer getCustomer(@PathParam("id")Integer id) { return(Customer)em.createNamedQuery("Customer.findByCustomerId").setParameter("customerId", id).getSingleResult();}

    #$s met$od s nvo)ed &$enever t$e 4E# resource s accessed usng H## GE# and t$eepected response t'pe s ;L.

    :otce t$e %ollo&ng ponts=

    #$e @GETannotaton ensures t$at t$s met$od s nvo)ed &$en t$e resource s

    accessed usng t$e H## GE# met$od. #$e @Path({id})de%nes a sub-resource suc$ t$at t$e resource de%ned b' t$s

    met$od can be accessed at customers/{id}&$ere *d s t$e varable part o% t$e4( and s mapped to t$e *d parameter o% t$e met$od as de%ned b' @PathParamannotaton.

    #$e @Producesannotaton ensures t$at an ;L representaton s generated. #$s &ll

    &or) as @XmlRootElementannotaton s alread' added to t$e generated entt'.

    2 t$e mports b' ta)ng t$e de%ault values %or all

    ecept %or @Produces. #$s annotaton needs to beresolved %rom t$e javax.ws.rspac)age as s$o&n.

    1*.$#$e 4E#%ul resource s no& accessble usng t$e %ollo&ng %ormat=

    $ttp=//RHO#B=RO4#B/ RCO:#E;#-4OO#B/R4EO4CE-0AE-4(B/R4EO4CE-4(B/R0-4EO4CE-4(B/R9A4(A0LE-A4#B

    #$e RCO:#E;#-4OO#B s t$e contet root o% t$e &eb applcaton. #$e R0-4EO4CE-4(B ma' be optonal n some cases. #$e R9A4(A0LE-A4#B s t$e part t$at s bound to t$e

    parameters n Java met$od.

    11

  • 5/26/2018 Java EE 6 Hands-on Lab

    34/47

    Java EE 6 Hands-on Lab

    (n our case, t$e 4( &ll loo) l)e=

    $ttp=//local$ost=D3D3/JavaEE6ampleApp/rest%ul/customers/ SdT&$ere {id}s t$e customerd s$o&n n t$e J2 page earler. o accessng

    *$ttp=//local$ost=D3D3/JavaEE6ampleApp/rest%ul/customers/! n a bro&ser dspla's t$eoutput as s$o&n.

    Accessng t$s 4( n t$e bro&sers euvalent to ma)ng a GE#reuest to t$e servce. #$s can bever%ed b' ve&ng t$e H##$eaders generated b' t$ebro&sers as s$o&n F*#ools,*7eveloper #ools n C$rome.

    1*.*Eac$ resource can berepresented n multple %ormats. C$ange t$e @Producesannotaton n

    1

    http://localhost:8080/JavaEE6SampleApp/restful/customers/http://localhost:8080/JavaEE6SampleApp/restful/customers/%7Bid%7Dhttp://localhost:8080/JavaEE6SampleApp/restful/customers/%7Bid%7Dhttp://localhost:8080/JavaEE6SampleApp/restful/customers/1http://localhost:8080/JavaEE6SampleApp/restful/customers/http://localhost:8080/JavaEE6SampleApp/restful/customers/%7Bid%7Dhttp://localhost:8080/JavaEE6SampleApp/restful/customers/1
  • 5/26/2018 Java EE 6 Hands-on Lab

    35/47

    Java EE 6 Hands-on Lab

    CustomerSessionBean.java%rom=

    @Produces("application/xml")

    to

    @Produces({"application/xml", "application/json"})

    #$s ensures t$at an ;L or JO: representaton o% t$e resource can be reuested b' aclent. #$s can be easl' ver%ed b' gvng t$e %ollo&ng command Fs$o&n n bold on acommand-lne=

    curl -H >)cce't# a''lication9 &tt'#99local&ost#009JavaEE6"a!'le)''9restful9custo!ers91 -vU About to connectF to local$ost port D3D3 FV3U #r'ng ==!... connected

    U Connected to local$ost F==! port D3D3 FV3B GE# /JavaEE6ampleApp/rest%ul/customers/! H##/!.!B ser-Agent= curl/R ;-o&ered-0'= ervlet/1.3 J/"." FGlass2s$ erver Open ource Edton 1.!.! Java/Apple (nc./!.6R erver= Glass2s$ erver Open ource Edton 1.!.!R Content-#'pe= applcaton/8sonR #rans%er-Encodng= c$un)edR 7ate= #ue, 3D :ov "3!! !==" G#R

    U Connecton V3 to $ost local$ost le%t ntactU Closng connecton V3SWaddressW=SWaddresslne!W=W!!! E. Las Olvas 0lvdW,Waddresslne"W=Wute !W,Wct'W=W2ortLauderdaleW,WstateW=W2LW,W+pW=SWareaLengt$W=W

  • 5/26/2018 Java EE 6 Hands-on Lab

    36/47

    Java EE 6 Hands-on Lab

    1+.0 Jerse Client )I to )ccess t&e /E"Tful /esource

    Jerse' s t$e 4e%erence (mplementaton o% JA;-4. #$e Jerse' Clent A( s an eas'-to-useand $g$-level Java A( t$at can $elp 'ou &rte clents %or an' H##-based 4E#%ul 5eb

    servce.

    #$s secton &ll create a clent t$at &ll access t$e 4E#%ul resource publs$ed at t$e/customers/{id}pat$.

    1+.14g$t-clc) on t$e pro8ect, select *:e&, *Java Class..., gve t$e class name as*4E#%ulClent, ta)e all ot$er de%aults, and clc) on *2ns$.

    1+.2Add t$e %ollo&ng code to t$e generated class=

    public static void main(String[] args) { String BASE_URL ="http://localhost:8080/JavaEE6SampleApp/restful/customers/"; Client client = Client.create(); WebResource resource = client.resource(BASE_URL + "1"); resource.addFilter(new LoggingFilter()); resource.get(String.class);

    resource.accept(MediaType.APPLICATION_JSON).get(String.class); }

    :otce t$e %ollo&ng ponts=

    #$s code creates a ne& Jerse' clent runtme nstance. #$s s an epensve ob8ect

    and so must be saved % no ot$er con%guraton s reured to access t$e resources. A ne& WebResources created per 4E#%ul resource t$at s capable o% buldng

    reuests to send to t$e resource and processng responses returned %rom t$eresource. Eac$ WebResource%ollo&s a bulder pattern to spec%' t$e reured (Et'pe n t$e response, application/jsonn t$s case.

    A LoggingFilters added to t$e resource to prnt t$e reuest and response

    messages. #$e code t$en reuests a de%ault and JO: representaton o% t$e resource n t&o

    separate calls.

    2 t$e mports b' ta)ng all t$e de%aults.

    1+.$4g$t-clc) on t$e %le and select *4un 2le to see t$e %ollo&ng output=

    16

  • 5/26/2018 Java EE 6 Hands-on Lab

    37/47

    Java EE 6 Hands-on Lab

    run:Nov 8, 2011 10:15:43 PM com.sun.jersey.api.client.filter.LoggingFilter logINFO: 1 * Client out-bound request1 > GET http://localhost:8080/JavaEE6SampleApp/restful/customers/1

    Nov 8, 2011 10:15:43 PM com.sun.jersey.api.client.filter.LoggingFilter log

    INFO: 1 * Client in-bound response1 < 2001 < Date: Tue, 08 Nov 2011 21:15:43 GMT1 < Content-Length: 6011 < Content-Type: application/xml1 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1Java/Apple Inc./1.6)1 < Server: GlassFish Server Open Source Edition 3.1.11 GET http://localhost:8080/JavaEE6SampleApp/restful/customers/12 > Accept: application/json

    Nov 8, 2011 10:15:43 PM com.sun.jersey.api.client.filter.LoggingFilter logINFO: 2 * Client in-bound response2 < 2002 < Transfer-Encoding: chunked2 < Date: Tue, 08 Nov 2011 21:15:43 GMT2 < Content-Type: application/json2 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1

    Java/Apple Inc./1.6)2 < Server: GlassFish Server Open Source Edition 3.1.12