Web Development in Java Part I Vítor E. Silva Souza (vitorsouza@inf.ufes.br) http://www.inf.ufes.br/ ~ vitorsouza Department of Informatics Federal University of Espírito Santo (Ufes), Vitória, ES Brazil
License'for'use'and'distribu0on' This'material'is'licensed'under'the'Crea0ve'Commons'' license'a9ribu0on:sharealike'4.0'interna0onal;' You'are'free'to'(for'any'purpose,'even'commercially):' Share:'copy'and'redistribute'the'material'in'any'' medium'or'format;' Adapt:'remix,'transform,'and'build'upon'the'material;' Under'the'following'terms:' A9ribu0on:'you'must'give'appropriate'credit,'provide'a'link'to' the'license,'and'indicate'if'changes'were'made.'you'may'do' so'in'any'reasonable'manner,'but'not'in'any'way'that'suggests' the'licensor'endorses'you'or'your'use;' ShareAlike:'if'you'remix,'transform,'or'build'upon'the' material,'you'must'distribute'your'contribu0ons'under'the' same'license'as'the'original.' More information can be found at: http://creativecommons.org/licenses/by-sa/4.0/ February'2014' Web'Development'in'Java' 2'
Outline'of'part'I' Basic'concepts:'what'are'Web'Applica0ons?' History'&'evolu0on'of'WebApps;' Quick'demonstra0ons;' Java'EE'Web'Profile;' Tools'for'Java'EE'Web'Profile'development;' Learning'in'prac0ce' 'the'java'hostel'demo:' Decora0on'with'Facelets;' Pages'and'controllers'in'JSF;' Wiring'components'with'CDI;' Persistence'with'JPA.' February'2014' Web'Development'in'Java' 3'
So'you ve'mastered'java ' What'about ' AWT/Swing, SWT, JavaFX? Android, Java ME, Java Card? Servlets, JSP, JSF, Facelets, CDI Java EE! Our focus: Java + Web February'2014' Web'Development'in'Java' 4'
What'is'a'Web'Applica0on?' A'distributed'system;' Access'via'a'Web'browser:' HyperText'Transfer'Protocol'(HTTP);' HTML,'JavaScript,'CSS,' ;' Popular'and'ubiquitous'user'client.' Similarity'to' vanilla '(non:web,'regular)'applica0ons:' Composed'of'GUI,'business'rules,'domain'data,' persistence'media,'etc.;' Can'range'from'a' Hello,'world! 'to'very'complex,' millions:of:users,'mlocs'systems.' According to http://www.informationisbeautiful.net/visualizations/million-linesof-code/, Facebook has ~ 60 MLOCs (including backend) February'2014' Web'Development'in'Java' 5'
It'started'with'the'(sta0c)'Web' Born'in'1989'as'a'more'effec0ve'communica0on'system' for'cern'(european'organiza0on'for'nuclear'research).' GET /index.html HTTP/1.0 Host: www.site.com [...] HTTP Request Looks for index.html file, merges with headers and sends back HTTP Response HTTP/1.1 200 OK Date: Fri, 15 Apr 2005 22:12:30 GMT Server: Apache/1.3.26 [...] Last-Modified: Wed, 23 Mar 2005 00:43:22 GMT Content-Length: 11379 Content-Type: text/html [...] Tim Berners-Lee, creator of the WWW February'2014' Web'Development'in'Java' 6'
Soon'enough'pages'were'built'dynamically' GET /index.cgi HTTP/1.0 Host: www.site.com [...] HTTP Request HTTP Response HTTP/1.1 200 OK Date: Fri, 15 Apr 2005 22:12:30 GMT Server: Apache/1.3.26 [...] Last-Modified: Wed, 23 Mar 2005 00:43:22 GMT Content-Length: 11379 Content-Type: text/html [...] 1: Runs a program associated with index.cgi; 2: Program returns text contents in HTML 3: Merges the result with HTTP headers and sends it back to client. February'2014' Web'Development'in'Java' 7'
Web'Development'was'born' Web'Development'consists'in'wri0ng'programs'that' respond'to'requests'using'http'and'produce'results'in' a'browser:compa0ble'language'(not'just'html!);' Many'components'involved:' The'Web'server;' The'Web'pages,'style'sheets,'scripts,'images,'etc.;' Code'in'a'programming'language;' Exis0ng'APIs,'frameworks,'libraries.' February'2014' Web'Development'in'Java' 8'
Evolu0on'of'Web'technologies' 1993:'CGI' 'Common'Gateway'Interface' 'C,'C++,' Fortran,'Perl,'etc.;' 1994:'Macromedia'Coldfusion,'PHP;' 1995:'Microsoq'ASP;' 1996:'Java'Servlets;' 1999:'JavaServer'Pages'(JSP);' ' Today:'Rich'Internet'Applica0ons' AJAX;' Flash'Ac0onScript;' HTML5,'etc.' February'2014' Web'Development'in'Java' 9'
A'brief'word'on'AJAX' AJAX'='Asynchronous'JavaScript'and'XML;' S0ll'request:response,'that'hasn t'changed!' JavaScript'makes'a'smaller'request,'using'an' object'called'xmlhttprequest;' Small'XML'chunks'are'exchanged'between' browser'and'server,'with'par0al'data;' The'webpage s'document'object'model' (DOM)'is'manipulated;' Only'parts'of'the'(X)HTML'page' are'changed'as'result.' We will see how to do this in Java! February'2014' Web'Development'in'Java' 10'
Evolu0on'of'Java'Web'technologies' 1995:'official'launch,'in'the'beginning'was'the'Applet;' 1996:'Java'Servlets;' 1999:'JavaServer'Pages'(JSP);' 1999:'J2EE'plauorm'(1.3'in'2001,'1.4'in'2003);' 2000:'Apache'Struts,'pioneer'MVC'framework;' 2004:'JavaServer'Faces;' 2006:'Java'EE'5;' 2009:'Java'EE'6;' 2013:'Java'EE'7.' February'2014' Web'Development'in'Java' 11'
Java'Servlets' 1) Read configuration: which class responds to this request? GET /hello HTTP Request web.xml HTTP Response Hello, World! The time now is 3) The method produces an appropriate response, to send back to client. Servlet Container 2) Instantiates the Servlet and calls the appropriate method. Servlet Business Logic February'2014' Web'Development'in'Java' 12'
Container???' A'container'is'a'soqware'that'manages'components' with'a'very'specific'lifecycle;' A'Servlet'(one'of'many'such'components):' Is'created'when'its'URL'is'requested;' Executes'a'method'that'corresponds'to'the'request;' Is'collected'by'the'GC'aqer'the'response.' Combined'with'a'soqware'that' talks 'in'http'through' a'port'(80,'8080,'etc.),'you'get'a'java'web'server.' February'2014' Web'Development'in'Java' 13'
Back'to'Servlets ' Not'necessarily'for'the'Web;' The'Web'Servlet,'the'most'used'one,'implements' javax.servlet.http.httpservlet:' doget(),'dopost(),'etc.;' init(),'destroy();' HttpServletRequest/Response;' response:'setcontenttype(),'getwriter().' February'2014' Web'Development'in'Java' 14'
Java'Servlets' Live Demo February'2014' Web'Development'in'Java' 15'
Comple0ng'the'Web'Applica0on' A'default'index.html' webpage;' A'form'in'the'page'sends' data'to'the'servlet:'name' of'the'visitor;' The'Servlet'now'says' Hello,'<visitor s'name> ' instead.' February'2014' Web'Development'in'Java' 16'
GET'and'POST'requests' Known as query string, this is how a GET request sends data. Let s try sending it via POST instead February'2014' Web'Development'in'Java' 17'
Fast'forward'to'Servlets'3.1 ' Annota0ons'for'URL'mapping;' Asynchronous'requests;' Non:blocking'I/O;' HTTP'upgrade'protocol;' Security'upgrades'against'session'fixa0on'a9acks;' Etc.' February'2014' Web'Development'in'Java' 18'
Servlets'are'annoying' Wri0ng'an'en0re'page'with'a'PrintWriter:' try (PrintWriter out = resp.getwriter()) { out.write("<html><head><title>hello!</title></head><body>"); out.write("<h1>hello, " + req.getparameter("visitor") + "!</h1>"); out.write("<p>the time now is " + new Date() + "</p>"); out.write("</body></html>"); } ' Map'Servlets'to'URLs:' @WebServlet(name = "HelloServlet", urlpatterns = {"/hello"}) (Also, remember that initially Servlets had to be mapped in web.xml!) February'2014' Web'Development'in'Java' 19'
JavaServer'Pages'(JSP)' 1) Looks for the helloworld.jsp file GET/POST /helloworld.jsp HTTP Request Web pages HTTP Response Hello, visitor! The time now is 3) The response looks like the execution of the page as a script (like PHP) Servlet Container 2) Automatically transforms the JSP in a Servlet and calls it Transformed Servlet Business Logic February'2014' Web'Development'in'Java' 20'
JSP'Standard'Tag'Library' Tag'Libraries'provide'tags'that'encapsulate'func0onality' common'to'many'jsp'applica0ons;' JSTL'defines'a'standard'set'of'tags'that'all'Java'Web' Servers'must'implement'(standardiza0on'effort):' Core:'variable'support,'flow'control,'URL' management,'miscellaneous;' XML:'XML'transforma0on'and'other'func0ons;' I18N:'locale'se{ng,'message'forma{ng,'number/ date'forma{ng;' SQL:'database'opera0ons;' Func0ons:'collec0on'length,'string'manipula0on.' February'2014' Web'Development'in'Java' 21'
JSP'Standard'Tag'Library' Examples:' <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:foreach var="item" items="${sessionscope.cart.items}">... </c:foreach> <c:set var="bookid" value="${param.remove}"/> <jsp:usebean id="bookid" type="java.lang.string" /> <% cart.remove(bookid); %> <sql:query var="books" datasource="${applicationscope.bookds}"> select * from PUBLIC.books where id =? <sql:param value="${bookid}" /> </sql:query> <c:url var="url" value="/catalog" > <c:param name="add" value="${bookid}" /> </c:url> <p><strong><a href="${url}"> February'2014' Web'Development'in'Java' 22'
Something'wrong'with'this'model ' Not'the'ideal'place'for'business'logic:' <html> [...] <% Connection conn; PreparedStatement stmt; conn = Database.connect(); stmt = conn.preparestatement("sql"); ResultSet rs = stmt.executequery(); // Business logic here... stmt = conn.preparestatement("sql"); stmt.executeupdate(); %> [...] </html> February'2014' Web'Development'in'Java' 23'
Model'2'or'MVC' GET/POST /hello.action HTTP Request HTTP Response Hello, visitor! The time now is *.action Servlet Container 1) Read configuration: which class responds to this request? some.xml 3) Depending on the response, chooses the appropriate view and sends it back to the client Front Controller 2) Instantiates and executes the action class. Action class Business Logic February'2014' Web'Development'in'Java' 24'
Model:View:Controller' Born'in'the'1970s'for'Smalltalk'in'the'Xerox'PARC;' Originally'for'GUIs'(Swing'also'based'on'it);' But'also'well:suited'for'the'Web:' Web'pages'and'other'Web'resources'are'the'view:' focus'on'presenta0on;' Your'business'logic'is'the'model:'informa0on'and' func0onality,'independent'of'presenta0on;' The'framework'and'your'ac0on'classes'are'the' controller:'mediator'between'model'and'view.' February'2014' Web'Development'in'Java' 25'
Example'in'Struts 2' <s:form namespace="/examples" action= calculateage" method="post"> <s:textfield label= Name" name= name" /> <s:textfield label= Birth date" name= birthdate" /> <s:submit value= Calculate Age" /> </s:form> public class CalculateAgeAction extends ActionSupport { private String name; private Date birthdate; private int age; // + getters and setters From the Struts 2 tag library, by the way } public String execute() throws Exception { age = calculatedifference(birthdate, new Date()); return SUCCESS; } <p>hello ${name}, you are ${age} years old.</p> This, instead, is FreeMarker February'2014' Web'Development'in'Java' 26'
Further'room'for'improvement ' Low'produc0vity'due'to'lack'of'reusable'components;' Vast'range'of'frameworks,'no'standard;' Lack'of'good'IDE'support'(related'to'previous'issues);' Separa0on'of'roles'could'be'further'improved.' February'2014' Web'Development'in'Java' 27'
JavaServer'Faces' Standard'specifica0on:'1.0,'1.1'in'2004,'1.2'in'2006' (Java'EE'5),'2.0'in'2008'(Java'EE'6);' Currently'in'version'2.2,'part'of'Java'EE'7;' Builds'on'the'idea'of'reusable'components;' Similar'to'an'MVC'framework:' Component:based'instead'of'ac0on:based;' Represents'UI'components'and'manages'their'state;' Event'handling;' Naviga0on'control;' Component'tag'library.' February'2014' Web'Development'in'Java' 28'
JSF'component'libraries' February'2014' Web'Development'in'Java' 29'
JSF'component'libraries' February'2014' Web'Development'in'Java' 30'
JavaServer'Faces' Live Demo February'2014' Web'Development'in'Java' 31'
Java'Edi0ons' Standard'Edi0ons:' Java'1.0'(1996);' Java'1.1'(1997);' J2SE'1.2'(1998);' J2SE'1.3'(2000);' J2SE'1.4'(2002);' Java'1.5'/'Java'5'(2004);' Java'SE'6'(2006);' Java'SE'7'(2011);' Java'SE'8'(expected'2014);' Java'SE'9'(expected'2016).' Enterprise'Edi0ons:' JPE'project'(1998);' J2EE'1.2'(1999);' J2EE'1.3'(2001);' J2EE'1.4'(2003);' Java'EE'5'(2006);' Java'EE'6'(2009);' Java'EE'7'(2013).' February'2014' Web'Development'in'Java' 32'
Java'for'the'enterprise' Sun'Microsystems'started'with'extensions'for' enterprise'java'customers.'examples:' JNDI:'Java'Naming'and'Directory'Interface;' JTS:'Java'Transac0ons'Service;' Loose'extensions'were'confusing'at'first,'so'eventually' Sun'joined'them'together'in'a'plauorm:'J2EE;' Sun'provided'the'spec,'a'reference'implementa0on'and' a'compa0bility'test'suite'to'cer0fy'applica0on'servers;' [Applica0on'Programming' 'Service'Provider]'Interface:' Programmers'write'code'to'the'API;' Vendors'implement'the'API'via'SPIs.' (In theory) February'2014' Web'Development'in'Java' 33'
Remember'containers?' Java'EE'applica0on'servers'are'also'containers'to:' Servlets;' Enterprise'Java'Beans;' Transac0ons;' Etc.' J2EE 1.2 JDBC Standard Extension API 2.0 Java Naming and Directory Interface Specification (JNDI) February'2014' Web'Development'in'Java' 34' 1.2 RMI-IIOP 1.0 Java Servlets 2.2 JavaServer Pages (JSP) 1.1 Enterprise JavaBeans (EJB) 1.1 Java Message Service API (JMS) 1.0 Java Transaction API (JTA) 1.0 JavaMail API 1.1 JavaBeans Activation Framework (JAF) 1.0
Enterprise'Java'Beans' At'the'core'of'J2EE:' Session'EJBs'provided'func0onality;' En0ty'EJBs'represented'domain'concepts'and' provided'persistence;' Message:driven'EJBs'respond'to'events.' Unfortunately,'it'suffered'a'lot'of'problems:' Very'complex'API,'driqed'away'from'OO;' Persistence'of'En0ty'EJBs'was'terrible;' Poor'performance.' Trivia: EJB-OSS! JBOSS! JBoss Got'eventually'replaced'by' lightweight 'frameworks,' such'as'hibernate'and'spring'framework.' February'2014' Web'Development'in'Java' 35'
De'facto'vs.'de'jure' Popularity'of'frameworks'led'to'a'major'change'of' standards;' Beginning'in'Java'EE'5,'many'of'its'technologies'were' inspired 'by'frameworks:' JPA'is'just'like'Hibernate'(Gavin'King'led'the'spec);' CDI'uses'dependency'injec0on,'like'Spring;' Facelets'provides'decora0on'like'Sitemesh/Tiles;' JSF'has'MVC:like'behavior.' If you can t win February'2014' Web'Development'in'Java' 36'
Java'EE'6:'pruning'and'Web'Profile' Bean Validation CDI (Contexts and Dependency Injection) for the Java EE Platform EL (Expression Language) Java EE 6 Web Profile Common Annotations for the Java Platform EJB (Enterprise Java Beans) Lite Entity Beans JACC (Java Authorization Service Provider Contract for Containers) Java EE Deployment API JavaMail JAX-RS (Java API for RESTful Web Services) JAXR (Java API for XML Registries) JMS (Java Messaging Service) JSF (JavaServer Faces) JSTL (Standard Tag Library for JavaServer Pages) Managed Beans Interceptors JASPIC (Java Authentication Service Provider Interface for Containers) Java EE Management API JAX-RPC (Java API for XML-based RPC) JAXB (Java Architecture for XML Binding) JCA (Java EE Connector Architecure) JPA (Java Persistence API) JSP (JavaServer Pages) JTA (Java Transaction API) Web Services Metadata for the Java Platform Servlet February'2014' Web'Development'in'Java' 37'
My'proposed'architecture' Facelets Primefaces Web pages Entities JSF JPA Managed Beans Session Beans DAOs CDI February'2014' Web'Development'in'Java' 38'
Tools/for/Java/EE/development/ Installing'and'configuring'the'database,'IDE'and' applica0on'server' February'2014' Web'Development'in'Java' 39'
Vast'assortment'of'tools' IDEs Application Servers Database Management Systems And these are just some examples February'2014' Web'Development'in'Java' 40'
Our'choice'for'this'tutorial' WildFly 8 CR1 (formerly JBoss Application Server) http://wildfly.org Eclipse IDE 4.3.1 (Kepler) http://www.eclipse.org MySQL Community Server 5 http://www.mysql.com February'2014' Web'Development'in'Java' 41'
Eclipse'4.3.1' February'2014' Web'Development'in'Java' 42'
Eclipse'4.3.1' Download'Eclipse'IDE'for'Java'EE'Developers;' Make'sure'you'check'the'OS'version;' Unpack;' Execute.' February'2014' Web'Development'in'Java' 43'
WildFly'8'CR1' February'2014' Web'Development'in'Java' 44'
WildFly'8'CR1' Download;' Unpack;' Manual'opera0on:' Start'it'via'scripts'inside'bin/'folder;' Deploy'applica0ons'by'copying'them'to'standalone/ deployments/'folder;' Alterna0vely,'integrate'with'Eclipse'with ' February'2014' Web'Development'in'Java' 45'
'JBoss'Tools' Integrate'Eclipse'&'WildFly:' Help'>'Install'New'Soqware ;' Work'with:'h9p://download.jboss.org/jbosstools/ updates/stable/kepler/;' Install'JBoss'Web'and'Java'EE'Development''>' JBossAS'Tools,'restart'Eclipse;' File'>'New'>'Other '>'Server'>'Server;' Select'WildFly'and'point'to'the'server s'directory.' Deploy/undeploy,'start/stop' the'server'from'eclipse.' February'2014' Web'Development'in'Java' 46'
MySQL'Community'Server'5' February'2014' Web'Development'in'Java' 47'
MySQL'Community'Server'5' Run'installer:' MacOS'DMG,'Windows'MSI,'Debian'DEB,'etc.;' Also'install'the'MySQL'WorkBench:' h9p://dev.mysql.com/downloads/tools/workbench/' You'will'also'need'MySQL'Connector/J:' h9p://dev.mysql.com/downloads/connector/j/' Make'sure'the'MySQL'server'is'running'for'the'tutorial' (instruc0ons'depend'on'opera0ng'system).' February'2014' Web'Development'in'Java' 48'
Giving'WildFly'a'way'to'connect'to'MySQL' February'2014' Web'Development'in'Java' 49'
Giving'WildFly'a'way'to'connect'to'MySQL' Contents'of'module.xml:' Folder structure <?xml version="1.0" encoding="utf-8"?> <module xmlns="urn:jboss:module:1.1" name="com.mysql"> <resources> <resource-root path="mysql-connector-java-5.1.29-bin.jar"/> </resources> <dependencies> <module name="javax.api"/> </dependencies> </module> MySQL Connector/J depends on basic Java EE APIs Name of the JAR file inside modules/com/mysql/main February'2014' Web'Development'in'Java' 50'
The/Java/Hostel/tutorial/ Developing'a'Java'EE'Web'Profile'applica0on'from'scratch.' An'overview'of'basic'Java'EE'6'Web'Profile'technologies.' February'2014' Web'Development'in'Java' 51'
Learn'by'example' Overview'of'some'of'the'main'Java'EE'(Web'Profile)' technologies:'jsf,'facelets,'cdi,'jpa;' Development'of'a'simple'but'real'applica0on:'the' website'for'a'hostel;' Detailed'instruc0ons'(a'bit'outdated)'in'my'blog:' h9p://www.inf.ufes.br/~vitorsouza/blog/developing: a:java:ee:6:web:profile:applica0on:from:scratch' Other'resources:' h9ps://github.com/feees/sigme/wiki/como:obter:e: executar:o:sigme'(in'portuguese);' h9ps://github.com/nemo:ufes/nemo:u0ls/wiki.' February'2014' Web'Development'in'Java' 52'
We'need'a'database'and'user' February'2014' Web'Development'in'Java' 53'
We'need'a'database'and'user' Database: javahostel User: javahostel Password: javahostel February'2014' Web'Development'in'Java' 54'
We'also'need'a'data'source'in'WildFly' Change'standalone/configura0on/standalone.xml:' <subsystem xmlns="urn:jboss:domain:datasources:2.0"> <datasources> <datasource jndi-name="java:jboss/datasources/javahostel" poolname="javahostelpool" enabled="true" jta="true" use-javacontext="true" use-ccm="true"> <connection-url> jdbc:mysql://localhost:3306/javahostel </connection-url> <driver>mysql</driver> <security> <user-name>javahostel</user-name> <password>javahostel</password> </security> </datasource> <drivers> <driver name="mysql" module="com.mysql"/> </drivers> </datasources> February'2014' Web'Development'in'Java' 55'
Ready!'What s'the'plan?' Create'the'project'with'the'appropriate'configura0on;' Apply'a'decorator'so'it'looks'good'right'away;' Facelets Write'domain'classes'and'create'the'DB'schema;' JPA Implement'the'guest'registra0on'feature.' JSF CDI JPA February'2014' Web'Development'in'Java' 56'
1':'Ini0al'project'configura0on' Some'Java'EE'technologies'require'configura0on:' JSF:'' WEB:INF/faces:config.xml;' Resource'bundles,'locale,'naviga0on'rules,'etc.;' Not'used'in'JavaHostel;' JPA:' META:INF/persistence.xml;' Data'source,'persistence'provider'and'its'proper0es.' February'2014' Web'Development'in'Java' 57'
How'does'it'work?' Mul0ple'JPA'providers:' The'container'has'one'(or'more)'implementa0on(s):' WildFly'"'Hibernate,'GlassFish'"'EclipseLink;' You'can'add'your'favorite'one'to'the'container;' JPA'Providers'are'not'standard'(persistence.xml'is):' Hibernate:'hibernate.hbm2ddl.auto'='create;' EclipseLink:'eclipselink.ddl:genera0on'='create:tables;' Once'JPA'is'configured,'the'container'is'ready'to'provide' us'with'an'en0ty'manager,'which'can'perform'orm' opera0ons'(we ll'get'there);' JSF'just'needs'the'configura0on'file'to'be'there ' February'2014' Web'Development'in'Java' 58'
2':'Let s'decorate'with'facelets' Download'an'exis0ng'template'(or'make'your'own):' h9p://www.templatemo.com/preview/ templatemo_104_hotel;' Create'a'decorator'file:'HTML'file'with'placeholders'' for'parts'of'the'page;' Apply'the'decorator'to'all'pages;' You'can'have'different'decorators'for'different' sec0ons,'different'users/roles,'etc.;' We'will'use'XHTML'(HTML'+'XML)'from'now'on.' Trust'me,'it s'be9er.' February'2014' Web'Development'in'Java' 59'
How'does'it'work?' Facelets'is'based'on'JSF:' xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" The'decorator'is'a'standard'(X)HTML'page,'but:' <h:body>'and'<h:head>'allow'jsf'features'to'work;' Tags'in'the'decorator'show'where'content'goes:' <ui:insert name="title" /> <ui:insert name="contents">blank page.</ui:insert> Default value if page doesn t provide contents for a specific section. February'2014' Web'Development'in'Java' 60'
How'does'it'work?' Pages'that'use'the'decorator'are'not'HTML'documents,' but'facelets'composi0ons:' <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" template="/resources/decorator.xhtml"> Pages'only'need'to'worry'about'their'contents.'No'need' to'repeat'layout'code:' <ui:define name="title">welcome</ui:define> <ui:define name="contents"> <h1>welcome to JavaHostel</h1> <p>under development.</p> </ui:define> CSS'also'helps'a'lot ' February'2014' Web'Development'in'Java' 61'
3':'Let s'talk'about'the'domain' Implement'the'following'domain'classes,'plus'tell'JPA' how'to'map'them'to'rela0onal'database'tables:' February'2014' Web'Development'in'Java' 62'
How'does'it'work?' Each'class'that'maps'to'the'RDB'is'called'an'En0ty:' @Entity public class... Although'not'mandatory,'en00es'should'have'ar0ficial' IDs'to'serve'as'PKs'(again,'trust'me,'it s'be9er):' @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; Simple'a9ributes'need'no'annota0on'(but'if'must,'you' can'use'@basic):' @Basic private String name; February'2014' Web'Development'in'Java' 63'
How'does'it'work?' Dates'can'store'date:only,'0me:only'and'date/0me:' @Temporal(TemporalType.DATE) private Date birthdate; Associa0ons'can'be'one:to:many,'many:to:one'and' many:to:many.'use'standard'collec0ons:' @ManyToOne private Guest guest; @OneToMany private Set<Bed> beds; Bi:direc0onal'associa0ons'need'to'be'connected'with' the'other'side'(or'there'will'be'2'associa0ons!):' @OneToMany(cascade = CascadeType.ALL, mappedby = "room") private Set<Bed> beds; February'2014' Web'Development'in'Java' 64'
4':'We'need'to'create'the'DB'tables ' Do'we'really?' February'2014' Web'Development'in'Java' 65'
How'does'it'work?' <property name="hibernate.hbm2ddl.auto" value="create"/> For even the very wise cannot see all ends. February'2014' Web'Development'in'Java' 66'
5':'Let s'actually'do'something ' Guest'registra0on:' Guest'enters'her'name,'birthDate,'email'and' password;' If'guest'is'underage,'display'a'message'explaining' minors'cannot'register;' Otherwise,'save'the'informa0on'in'the'database'and' display'a'success'message.' February'2014' Web'Development'in'Java' 67'
February'2014' Web'Development'in'Java' 68'
How'(the'****)'does'it'work?' JSF Page JSF Expression Language / CDI JSF Controller <h:inputtext id="name" value="#{registrationcontroller.guest.name}" size="30" /> <h:inputtext id="birthdate" value="#{registrationcontroller.guest.birthdate}" size="10"> <f:convertdatetime pattern="dd/mm/yyyy" /> </h:inputtext> JSF Converters! <h:commandbutton action="#{registrationcontrolle r.register}" value="register" /> @Named public class RegistrationController implements Serializable {... Guest getguest()...... String register()...... getname()...... setname()...... getbirthdate()...... setbirthdate()... Guest.java February'2014' Web'Development'in'Java' 69'
JSF'page'<:>'controller'communica0on' Whenever'a'JSF'page'is'rendered,'EL'is'interpreted:' I.e.,'#{registra0onController.guest.name}'becomes' registra0oncontroller.getguest().getname();' The'registra0onController'object'is'created'for'you;' When'you'send'the'next'request'to'the'server,'JSF'will' update'the'state'of'the'components'at'the'controller:' I.e.,'registra0onController.getGuest().setName(n)'is' called,'where'n'='contents'of'the'field;' This'happens'in'any'request,'not'only'the'ones'that' call'registra0oncontroller.somemethod()!' If'the'field'has'a'forma9er,'it'parses/formats'the'data.' February'2014' Web'Development'in'Java' 70'
Enters'CDI' Why'is'this'par0cular'class'instan0ated'when'the'EL' refers'to'registra0oncontroller?' @Named'creates'a'default'EL'reference;' You'can'change'the'default:'@Name("regCtrl");' When'is'this'object'created?'How'many'are'created?' @SessionScoped'='one'per'session'(client);' There'are'other'scopes:'request,'conversa0on,' applica0on,'flash'(this'last'one'is'jsf,'not'cdi);' There'is'much'more'to'CDI ' February'2014' Web'Development'in'Java' 71'
CDI'meets'EJBs' JSF Controller CDI everywhere Inject RegistrationService EJB @EJB private RegistrationService registrationservice; registrationservice.register(gu est); @Stateless @LocalBean public class RegistrationService... @PersistenceContext private EntityManager entitymanager; entitymanager.persist(guest); Entity Manager provided by the application server (WildFly provides Hibernate) February'2014' Web'Development'in'Java' 72'
EJB'stuff' @Stateless'='no'state'='no'object'a9ributes;' The'container'can'have'a'share'pool'of'instances;' To'store'state,'use'@Stateful,'then'give'it'a'scope;' An'EJB'can'also'be'@Singleton'now;' @LocalBean'means'the'EJB'is'not'split'between' interface'and'implementa0on;' Now'that'I'think'about'it,'it' should'have'been ' Remote'vs.'local' interface.' February'2014' Web'Development'in'Java' 73'
Back'to'JSF' Where'to'go'aqer'the'controller'executes?' catch (UnderAgeGuestException e) { age = e.getage(); return "/registration/underage.xhtml"; } return "/registration/success.xhtml"; Returning'null'or'void,'the'same'page'is'reloaded;' You'can'also'have'naviga0on'rules'in'faces:config.' Data'from'the'controller'is'shown'in'the'result'page:' <p>dear <h:outputtext value="#{registrationcontroller.guest.name} />, unfortunately underage people are not allowed to register as guests and, according to your birth date, you have only <h:outputtext value="#{registrationcontroller.age}" /> years.</p> <p>dear <h:outputtext value="#{registrationcontroller.guest.name} />, welcome to JavaHostel.</p> February'2014' Web'Development'in'Java' 74'
Next' More'on'JSF:'AJAX'support,'converters,'forma9ers,' i18n,'facelets'components,'etc.;' More'on'CDI:'scopes,'producers,'qualifiers,' interceptors,'decorators,'events,'etc.;' More'on'JPA:'element'collec0ons,'bean'valida0on,' JPQL,'criteria'API,'etc.;' More'on'EJBs:'authoriza0on,'local/remote'interfaces,' singleton'ejbs,'asynchronous'invoca0ons,'etc.;' Use'a'JSF'component'library'(e.g.,'PrimeFaces).' February'2014' Web'Development'in'Java' 75'
h9p://nemo.inf.ufes.br/' February'2014' Web'Development'in'Java' 76'