Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Enterprise Web App. Development (4): JSF with CDI Training

Enterprise Web App. Development (4): JSF with CDI Training

This is the fourth course of a series of courses for Enterprise Web Application development based on several Open Source products. As we finished open source development tool courses, we are going to move on to “JSF with CDI” as the first course of Jakarta EE framework specification. Later we are taking care of “JPA + JTA with CDI”, “JAX-RS” and “Jakarta Batch” as minimum skills to develop Enterprise Web Application. In those courses, we refer to some “Application Architecture Design Patterns”. Therefore this series require the basic skills of Windows 10, CentOS, Eclipse IDE, Java SE (Oracle JDK or OpenJDK), Payara Server and PostgreSQL. Regarding the Payara Server, we can use another Web Application Server conforming to Jakarta EE specification. As for PostgreSQL, we might be able to use another RDBMS product instead. We can also make use of another Linux distribution instead of CentOS.

E7d0d73badb1cc1df2bc44f58d51aaff?s=128

Koichi NAKAGAWA

November 26, 2020
Tweet

Transcript

  1. JAKARTA SERVER FACES (JSF) WITH CDI A part of Jakarta

    EE specification Rich Component Based MVC Framework 1 By Koichi NAKAGAWA
  2. Jakarta Server Faces Jakarta Server Faces (JSF) with CDI 2

  3. EWA development course curriculum Object Oriented Development Methodology JSF with

    CDI JPA + JTA with CDI JAX-RS Application Architecture Design Patterns Eclipse IDE™ Version Control Tool with Git™ Build Tool with Apache Maven™ Payara Server™ Administration Windows 10™ + Linux (CentOS™) Total EWA Development Exercise Jakarta Batch Java SE (Oracle JDK™/OpenJDK™) Required Skills to take courses Test Tool with JUnit5 PostgreSQL™ Administration 3
  4. Trademarks Notice • Jakarta™ EE and their logo( ) are

    trademarks of the Eclipse Foundation. • Payara™ Server and their logo( ) are trademarks of Payara Services® LTD. • PrimeFaces™ is trademarks of Prime Tek Informatics. • Eclipse IDE for Enterprise Java Developer™, the Eclipse IDE for Enterprise Java Developer ™ logo( ) are trademarks of the Eclipse Foundation. • Apache Maven™, Maven™ are trademarks of the Apache Software Foundation (ASF). • Eclipse M2Eclipse™, M2Eclipse™ are trademarks of the Eclipse Foundation. • Git™ and the Git™ logo( ) are either registered trademarks or trademarks of Software Freedom Conservancy, Inc., corporate home of the Git Project, in the United States and/or other countries. • Eclipse GitTeam Provider™, Eclipse EGit™, EGit™ is trademark of the Eclipse Foundation. • Eclipse Java development tools™, Java development tools™, Eclipse JDT™, JDT™ are trademarks of the Eclipse Foundation. • Java™ is trademark of Oracle Corporation. 4
  5. Assumption for this course • The trainees who take this

    course are required the following skills in advance • Payara Server (Version: 5.2020.5) – Basic Administration Operations • Oracle JDK/OpenJDK (Version: 8) • Eclipse IDE for Enterprise Java Developers (Version: 2020-09 (4.17.0)) • Build Tool Training Course • Version Control Tool Training Course • Test Tool Training Course 5
  6. Objectives This course is aimed to obtain the following skills

    • Jakarta Server Faces (JSF) technology • Jakarta Contexts and Dependency Injection (CDI) technology as components in presentation layer • Development web interface applications using above JSF and CDI 6
  7. Jakarta Server Faces • Jakarta Server Faces (JSF) with Jakarta

    Contexts and Dependency Injection (CDI) Basics • First JSF Web Application • CDI Scopes • Menu Layout and Template • Other Topics 7
  8. Jakarta Server Faces (JSF) with Jakarta Contexts and Dependency Injection

    (CDI) Basics 8
  9. Concept of Web Communication • Basic Web Access to Static

    Contents on Server Networks Browser (Chrome, Firefox, Edge, …) Web Application Server hello.html Server (URL: http://xxx.com/hello.html) Hello World! 1. Enter URL (http://xxx.com/hello.html) 2. Get Resource (http://xxx.com/hello.html) 3. Receive Resource (HTML) 4. Show Resource (HTML) HTTP Request HTTP Response 9
  10. Concept of Web Communication • Basic Web Access to Dynamic

    Contents on Server Networks Browser (Chrome, Firefox, Edge, …) Web Application Server Server (URL: http://xxx.com/hello/) Hello World! 1. Enter URL (http://xxx.com/hello/) 2. Get Resource (http://xxx.com/hello/) 4. Receive Resource (HTML) 5. Show Resource (HTML) Servlet HTML 3. Generate HTML HTTP Request HTTP Response 10
  11. Concept of Web Communication • Basic Web Access to Template

    based Dynamic Contents on Server Networks Browser (Chrome, Firefox, Edge, …) Web Application Server Server (URL: http://xxx.com/hello/) Hello World! 1. Enter URL (http://xxx.com/hello/) 2. Get Resource (http://xxx.com/hello/) 4. Receive Resource (HTML) 5. Show Resource (HTML) Servlet HTML 3. Generate HTML Template (JSP) HTTP Request HTTP Response 11 Template (Facelets)
  12. Concept of MVC • Model-View-Controller (MVC) Components Web Application Server

    Presentation Layer Business Layer Controller View Model HTTP Request Invoke Forward Refer HTTP Response 12
  13. Concept of JSF • Jakarta Server Faces (JSF) : Components

    based MVC Framework Web Application Server (Jakarta EE Container) Presentation Layer Business Layer JSF Servlet (Controller) JSF Facelets (View) CDI Component (Model) HTTP Request Invoke Forward Refer HTTP Response 13
  14. Concept of JSF • 2 Types of CDI Components :

    Components in Presentation Layer and Business Layer Web Application Server (Jakarta EE Container) Presentation Layer JSF Servlet (Controller) JSF Facelets (View) CDI Component (Model) Invoke Forward Refer Business Layer CDI Component (Model) Invoke Handle Presentation Logics Handle Business Logics 14
  15. Home page (HTML) Login page (HTML) Binding JSF Facelets and

    CDI Components • Binding to methods and properties in CDI Components Web Application Server (Jakarta EE Container) Presentation Layer @Named(“authBean”) Class AuthBean { : private String prop1 = “”; : public String hello() { prop1 = “Hello !!!”; return “home”;} : public String getProp1() {return prop1;} : } Login JSF Servlet (Controller) : <p:commandButton value=“Login” action=“#{authBean.hello}” /> : : <h:outputText value=“#{authBean.prop1}” /> : CDI Component (“authBean”) JSF Facelets (“index.xhtml”) JSF Facelets (“home.xhtml”) Hello !!! Browser 15
  16. Login page (HTML) CDI Component (View) CDI Component (View) CDI

    Component (View) JSF Control Flows and View Navigation • Overall JSF Control Flows Web Application Server (Jakarta EE Container) Presentation Layer JSF Servlet (Controller) JSF Facelets (View) CDI Component (View) 2. Invoke a CDI Component by CDI Name and its Method (ex. authBean#login()) 5. Forward JSF Facelets (View) JSF Facelets (View) JSF Facelets (View) 4. Return View Name (ex. “home”) Facelet File Name (ex. home.xhtml) Login 1. HTTP Request 3. Execute AuthBean#login() Home page (HTML) 7. HTTP Response 6. Refer CDI Properties (ex. authBean#getProp1()) Hello !!! Browser 16
  17. Login page (HTML) CDI Component (View) CDI Component (View) CDI

    Component (View) JSF Control Flows and View Navigation • JSF View Navigation Web Application Server (Jakarta EE Container) Presentation Layer JSF Servlet (Controller) JSF Facelets (View) CDI Component (View) 2. Invoke a CDI Component by CDI Name and its Method (ex. authBean#login()) 5. Forward JSF Facelets (View) JSF Facelets (View) JSF Facelets (View) 4. Return View Name (ex. “home”) Facelet File Name (ex. home.xhtml) Login 1. HTTP Request 3. Execute AuthBean#login() Home page (HTML) 7. HTTP Response 6. Refer CDI Properties (ex. authBean#getProp1()) Hello !!! Browser 17
  18. JSF Control Flows and View Navigation • JSF Customized View

    Navigation : : <navigation-rule> <navigation-case> <from-outcome>home</from-outcome> <to-view-id>/homeMenu.xhtml</to-view-id> </navigateon-case> : : : <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/loginMenu.xhtml</to-view-id> </navigation-case> </navigation-rule> : WEB-INF/faces-config.xml Return String: home home.xhtml JSF Servlet (Controller) Return String: home homeMenu.xhtml Default Navigation Custom Navigation Facelets Facelets CDI Component (View) CDI Component (View) JSF Servlet (Controller) 18
  19. 2 way linkages of Servlet/JSP • How to link 2

    Servlets/JSP Linkage Benefits Constrains Link Style Action Link Communications Dispatch HTTP Request and HTTP Response can be passed Can link only to servlet/JSP on the same Web Application Forward rd.forward(request, response); Delegate the process to other Servlet/JSP Include rd.include(request, response); Add the output of other Servlet/JSP to the original output Redirect Can link to servlet/JSP on other Web Application HTTP Request and HTTP Response cannot be passed  Need to pass as Query Parameters response.sendRedir ect(path); Browser Jakarta EE Container Servlet/JSP Servlet/JSP HTTP Request HTTP Response Browser Jakarta EE Container Servlet/JSP Servlet/JSP HTTP Response HTTP Request Browser Jakarta EE Container Servlet/JSP HTTP Request HTTP Response(301 or 302) Jakarta EE Container Servlet/JSP HTTP Request HTTP Response JSF 19
  20. Navigation with MVC Framework • Invoking Programs by POST Method

    Including UPDATE (Default JSF Actions) Jakarta EE Container Presentation Layer Controller (JSF Servlet) View (JSF Facelets) HTTP Request (POST Method) Forward HTTP Response Menu Transit Category: Name: Product Information: [NOT Bookmarkable] Update Name Price Vendor Notes ABC 10,100 TY Co. JSF View(Facelets) Current Menu: <h:commandButton … action=“#{xyzBean.funcA}” /> Model(CDI): @Named public class XyzBean { : public String funcA() { : return “nextMenu”;} : } Current Menu Next Menu 20
  21. Navigation with MVC Framework • Invoking Programs by POST-REDIRECT-GET(PRG) Method

    including UPDATE Jakarta EE Container Presentation Layer Controller (JSF Servlet) View (JSF Facelets) HTTP Response Menu Transit Category: Name: Product Information: Update Name Price Vendor Notes ABC 10,100 TY Co. This PRG prevents “Double Submits for Update” issue by clicking “Reload” button on a browser. JSF View(Facelets) Current Menu: <h:commandButton … action=“#{xyzBean.funcA}” /> Model(CDI): @Named public class XyzBean { : public String funcA() { : return “nextMenu?faces- redirect=true”;} : } Current Menu Next Menu 21 Forward
  22. Navigation with MVC Framework • Invoking Programs by GET method

    for Reference Jakarta EE Container Presentation Layer Controller (JSF Servlet) View (JSF Facelets) HTTP Request (GET Method) Forward HTTP Response Menu Transit Category: Name: Search Results: [Bookmarkable] Search Name Price Vendor Notes ABC 10,100 TY Co. XYZ 2,000 HJ Ltd. JSF View(Facelets) Current Menu: <h:button outcome=“nextMenu” /> View(Facelets) Next Menu: <f:metadata> <f:viewAction action=“#{xyzBean.funcA}” /> </f:metadata> Model(CDI): @Named public class XyzBean { : public String funcA() { : return;} : } Current Menu Next Menu 22
  23. Filter Function • How to use Filter Function Jakarta EE

    Container Filter HTTP Request HTTP Response Servlet HTTP Request HTTP Response @WebFilter(urlPattern = “/loginProcessServlet”) Public class LoginProcessFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { (Pre-processing Code is here.) chain.doFilter(request, response); (Post-processing Code is here.) } } Pre-processing: - Check Validation of HTTP Session - Check “User-Agent” Post-processing: - Exception Handling Pre- & Post-processing: - Output logging Examples of Filtering Process 23
  24. DHTML and Ajax • What is DHTML? DHTML Technology: Dynamic

    restructure of DOM tree, structure of HTML elements, by monitoring several events like clicks, text inputs and mouse movements on a web browser. Client Side (Web Browser) DOM Tree body form div div input table tr td td Java Script Event Notification Update 24
  25. DHTML and Ajax Ajax Technology: Combination technology of DHTML and

    asynchronous communication with server side. Client Side (Web Browser) DOM Tree body form div div input table tr td td Java Script Event Notification Update XHR Server Side Asynchronous Call Call Back URL Encode, XML, JSON XML, JSON • What is Ajax? 25
  26. Ajax Technology • Ajax = Asynchronous JavaScript + XML Login

    page (HTML+JavaScript) Login Fail !!! Update Web Application Server JavaScript (XMLHttpRequest) Event XML, JSON,… XML, JSON,… RESTful Web Service Process Ajax Request and Return Response in XML, JSON, … Resource HTTP Request HTTP Response Retrieve Resource & Set Results Browser 26
  27. Login page (HTML+JavaScript) CDI Component (View) CDI Component (View) CDI

    Component (View) JSF with Ajax • JSF Action Flows with Ajax Web Application Server (Jakarta EE Container) Presentation Layer CDI Component (View) Login Execute AuthBean#hello() JSF Servlet (Controller) About JSF Facelet example : - ajax attribute is one of Primefaces CommandButton component attributes (ajax=“true” is default). Execute AuthBean#getProp1() AuthBean : : : <p:commandButton value=“Login” action=“#{authBean.hello}” ajax=“true” update=“out” /> : : <h:outputText id=“out” value=“#{authBean.prop1}” /> : : JSF Facelets (“index.xhtml”) 2. Update (Redraw) Browser 27 Fail !!!
  28. JSF Maven Structure • Sample Maven Directory Structure for Basic

    JSF Project project src main java [package] AuthBean.java webapp WEB-INF web.xml login.xhtml home.xhtml pom.xml Maven Configuration JSF Facelets Web Configuration CDI Components 28 Directory File
  29. Web Configuration • web.xml (1) <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1"

    xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <display-name>JSF Demo System</display-name> <description> This JSF demo program demonstrates the JSF. </description> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> <!-- <param-value>Production</param-value> --> </context-param> Control if the messages are displayed or not. (Default: Development) 29
  30. Web Configuration • web.xml (2) <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup>

    </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <session-config> <session-timeout>30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/login.xhtml</welcome-file> </welcome-file-list> </web-app> Define “Servlet Name” for JSF Controller “Servlet Class” Map “URL Pattern” to “Servlet Name” for JSF Controller 30
  31. JSF Facelets • Sample JSF Facelets Basics <?xml version='1.0' encoding='UTF-8'

    ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui" xmlns:c="http://java.sun.com/jsp/jstl/core"> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Login Menu</title> </h:head> <h:body> <h:form id="mainForm" prependId="false"> <p:panelGrid columns="2"> <p:outputLabel value="User Id:" for="userId" /> <p:inputText id="userId" value="#{authBean.userId}" /> <p:outputLabel value="Password:" for="password" /> <p:password id="password" value="#{authBean.password}" /> <f:facet name="footer"> <p:commandButton id="login" value="Login" action="#{authBean.login}"/> </f:facet> </p:panelGrid> </h:form> </h:body> </html> JSF Facelets (“login.xhtml”) 31
  32. JSF Facelets • Facelets Basics – Definitions <?xml version='1.0' encoding='UTF-8'

    ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui" xmlns:c="http://java.sun.com/jsp/jstl/core"> For JSF Standard tags For Primefaces™ tags For JSTL tags 32
  33. JSF Facelets • Facelets Basics – HTML Header <h:head> <meta

    http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Login Menu</title> </h:head> Set “Content-Type” Set Title 33
  34. JSF Facelets • Facelets Basics – HTML Body <h:body> <h:form

    id="mainForm" prependId="false"> <p:panelGrid columns="2"> <p:outputLabel value="User Id:" for="userId" /> <p:inputText id="userId" value="#{authBean.userId}" /> <p:outputLabel value="Password:" for="password" /> <p:password id="password" value="#{authBean.password}" /> <f:facet name="footer"> <p:commandButton id="login" value="Login" action="#{authBean.login}"/> </f:facet> </p:panelGrid> </h:form> </h:body> CDI Component (AuthBean) 34
  35. First JSF Web Application 35

  36. Exercise of First JSF Web Application • Menu Flows 

    In the “Login” menu, enter “User Id” and “Password” and click “Login” button.  If authentication succeeds, “Home” menu whose title is “Hello World” is shown displaying “User Id”. “Login” menu “Home” menu JSF Facelets (login.xhtml) JSF Facelets (home.xhml) 36 Exercise: Let’s make the First JSF Web Application.
  37. Exercise of First JSF Web Application • JSF Control Flows

    Web Application Server (Jakarta EE Container) Presentation Layer JSF Servlet (Controller) JSF Facelets (login.xhtml) CDI Component (AuthBean) 8. Forward JSF Facelets (home.xhml) 7. Return View Name (“home”) 4. HTTP Request 6. Execute AuthBean#login() 10. HTTP Response 5. Create AuthBean and set CDI Properties with authBean#setUserId(), authBean#setPassword() and invoke authBean#login() Browser 1. HTTP Request 2. Forward 3. HTTP Response 9. Refer CDI Property with authBean#getUserId() “Login” menu “Home” menu 37
  38. First JSF Web Application Development • Development Procedure on Eclipse™

    1. Switch Eclipse Workspace to “ws3”, if current Workspace is not “ws3”. 2. Copy the project of “test2” and paste it as “jsfproject”. 3. Delete packages of org.example.test2 including sources and add packages of org.example.jsfproject under src/main/java and src/test/java. 4. Change <url-pattern> of <servlet-mapping> to “/faces/*” and the value for <welcome-file> in web.xml should be “faces/login.xhtml”. 5. Rename the value of <artifactId> to “jsfproject”, the value of <name> to “${project.artifactId}” and add a <dependency> with “org.primefaces” as <groupId>, “primefaces” as <artifactId>, “8.0” as <version> in “pom.xml” . 6. Add a provided unit test program named “AuthBeanTest.java”. 7. Add another provided system test program named “LoginIT.java”. 8. Make RequestScoped Named CDI “AuthBean.java” under “org.example.jsfproject” which has properties of “userId” and “password” and their accessors and a method of “login” to pass the unit test above and execute the unit test. 9. Make “login.xhtml” and “home.xhtml” to pass the system test above and execute the system test. As for home.xhtml, we can reuse of existing “page2.xhtml” by copy and paste. 38
  39. First JSF Web Application Development • Project Explorer New New

    New Provided Provided Modify 39
  40. First JSF Web Application Development • Unit Test Program -

    AuthBeanTest.java package org.example.jsfproject; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class AuthBeanTest { @Test void testLogin() { AuthBean authBean = new AuthBean(); authBean.setUserId("testUser"); authBean.setPassword("test123"); String nextMenu = authBean.login(); assertEquals("home", nextMenu); } } 40
  41. First JSF Web Application Development • System Test Program -

    LoginIT.java package org.example.jsfproject; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import io.github.bonigarcia.seljup.SeleniumExtension; @ ExtendWith(SeleniumExtension.class) class LoginIT { @Test public void testOperations(ChromeDriver driver) throws InterruptedException{ String hostname = System.getProperty("servlet.host"); String port = System.getProperty("servlet.port"); String context = System.getProperty("servlet.context"); driver.get("http://" + hostname + ":" + port + "/" + context + "/"); WebDriverWait wait = new WebDriverWait(driver, 20); WebElement element = driver.findElement(By.id("userId")); element.sendKeys("testUser"); element = driver.findElement(By.id("password")); element.sendKeys("test123"); Thread.sleep(3000); element = driver.findElement(By.id("login")); element.click(); boolean isTitle = wait.until(ExpectedConditions.titleContains("Hello World")); assertTrue(isTitle); Thread.sleep(3000); } } 41
  42. CDI Scopes 42

  43. CDI Scope Types • Scope Types of CDI Components Web

    Application Server (Jakarta EE Container) Presentation Layer @XXXScoped @Name(“viewBean”) class ViewBean { : } CDI Component ScopeType Scope Description @ApplicationScoped Only one instance of the bean will exist in the entire application. After bean initialization, every time a client requests an instance of this bean the container will always provide the same bean instance. @SessionScoped An instance of this bean will exist per HTTP session. @ConversationScoped This kind of beans is used to represent a conversation between the client and the server. @RequestScoped An instance of this bean will exist per HTTP request. @ViewScoped Since this kind of beans keeps their state during the entire view life time, they become useful to build Ajax interactions between the client and the server in a conversational style. Once the view is changed to another view(next Facelets menu), the bean is discarded. 43
  44. Lifetime of CDI Scopes • Differences in lifetime of several

    CDI scopes Application Session Conversation Request View [HTTP Session] [HTTP Request] [Ajax Requests] Deploy App. Undeploy App. Access Session Scoped CDI Invalidate HTTP Session Begin Conversion Scoped CDI End Conversation Scoped CDI HTTP Request HTTP Response HTTP Request HTTP Response Ajax Ajax Ajax … … 44 Access View Scoped CDI “action” method returns String value to change view
  45. Application Scoped CDI • Access to “Application” Scoped CDI User

    A Product: XYZ Show Price Product: XYZ Price: 750 Confirm “Show Price” Product: ABC Show Price Product: ABC Price: 500 Confirm “Show Price” Application Scoped CDI User B Facelets (products.xhtml) Facelets (results.xhtml) Facelets (products.xhtml) Facelets (results.xhtml) 45
  46. Session Scoped CDI • Access to “Session” Scoped CDI Login:

    Password: userA ***** Login Welcome to XXX System! You are ‘userA’ Logout Logout from XXX System successfully. “Login” “Logout” Login: Password: userB ******* Login Welcome to XXX System! You are ‘userB’ Logout “Login” “Logout” Session Scoped CDI #1 Session Scoped CDI #2 User A User B Logout from XXX System successfully. Facelets (login.xhtml) Facelets (home.xhtml) Facelets (logout.xhtml) Facelets (login.xhtml) Facelets (home.xhtml) Facelets (logout.xhtml) 46
  47. Conversation Scoped CDI • How to maintain “Conversation” Product: ABC

    Cart Checkout Select the payment method. O Credit O Bank Transfer “Cart” “Checkout” Conversation Scoped CDI #1 (cid=XXX) Conversation Scoped CDI #2 (cid=YYY) Product: XYZ Cart “Cart” Checkout “Checkout” User A User B Facelets (shop.xhtml) Check the following items. - Product: ABC Facelets (cart.xhtml) Check the following items. - Product: XYZ Select the payment method. O Credit O Bank Transfer Facelets (payment.xhtml) Facelets (shop.xhtml) Facelets (cart.xhtml) Facelets (payment.xhtml) 47
  48. Request Scoped CDI • Access to “Request” Scoped CDI Product:

    Price: XYZ 750 Update Product: XYZ Price: 750 Confirm Price for Product: XYZ has updated. “Update” “Confirm” Product: Price: ABC 500 Update Product: ABC Price: 500 Confirm Price for Product: ABC has updated. “Update” “Confirm” CDI #1 User A User B CDI #2 CDI #3 CDI #4 Facelets (update.xhtml) Facelets (update.xhtml) Facelets (confirm.xhtml) Facelets (result.xhtml) Facelets (confirm.xhtml) Facelets (result.xhtml) 48
  49. View Scoped CDI • Access to “View” Scoped CDI “Prepare”

    “Update” View Scoped CDI #1 User A User B View Scoped CDI #2 Same Facelet (manageProduct.xhtml) Ajax Ajax Same Facelet (manageProduct.xhtml) Product Information: Name Price Vendor Notes ABC 10,100 TY Co. Product Information: Name Price Vendor Notes ABC 10,100 TY Co. Product Information: Name Price Vendor Notes ABC 7,500 TY Co. Product: Price: ABC 7,500 Update “Prepare” “Update” Ajax Ajax Product Information: Name Price Vendor Notes XYZ 12,100 TY Co. Product Information: Name Price Vendor Notes ABC 10,100 TY Co. Product Information: Name Price Vendor Notes XYZ 13,500 TY Co. Product: Price: XYZ 13,500 Update 49
  50. Exercise of Session Scoped CDI • Menu Flows In the

    “Home” menu, click “Logout” link.  HTTP Session is invalidated and move back to “Login” menu. “Login” menu “Home” menu JSF Facelets (login.xhtml) JSF Facelets (home.xhml) 50 Exercise: Let’s modify the JSF Web Application with Session Scoped CDI.
  51. Exercise of Session Scoped CDI • JSF Control Flows Web

    Application Server (Jakarta EE Container) Presentation Layer JSF Servlet (Controller) CDI Component (AuthBean) 5. Forward JSF Facelets (login.xhml) 4. Return View Name (“login”) 1. HTTP Request 3. Execute AuthBean#logout() 6. HTTP Response 2. Invoke authBean#logout() Browser “Login” menu “Home” menu 51
  52. Session Scoped CDI Development • Development Procedure on Eclipse™ 1.

    Revise “AuthBean.java” to specify @SessionScoped, implement Serializable and add a method of “logout” to invalidate HTTP Session using FacesContext.getCurrentInstance().getExternalContext().invalidateSession() and return to “login” menu . 2. Revise “home.xhtml” to add a link of “Logout” using a PrimeFaces’ component of <p:commandLink> inside a new <h:form> tag. 3. Replace the system test program named “LoginIT.java” with new one which clicks “Logout” link additionally. 52
  53. Session Scoped CDI Development • Project Explorer Modify Modify Provided

    (New Version) 53
  54. Session Scoped CDI Development • System Test Program - LoginIT.java

    @ ExtendWith(SeleniumExtension.class) class LoginIT { @Test public void testOperations(ChromeDriver driver) throws InterruptedException{ : element = driver.findElement(By.id("login")); element.click(); boolean isTitle = wait.until(ExpectedConditions.titleContains("Hello World")); assertTrue(isTitle); Thread.sleep(3000); element = driver.findElement(By.id("logout")); element.click(); isTitle = wait.until(ExpectedConditions.titleContains("Login Menu")); assertTrue(isTitle); Thread.sleep(5000); } } 54
  55. Session Scoped CDI Jakarta EE Container Presentation Layer HTTP Request

    HTTP Response (Set-Cookie:jsessionid=XXX) Session Scoped CDI Session Information Login ID: Password: Logout from XYZ System Login XYZ System Logout Servlet & Facelets HTTP Request (Cookie:jsessionid=XXX) HTTP Response HTTP Request (Cookie:jsessionid=XXX) HTTP Response … … Initiate Session Terminate Session Cookie is shared among multiple tabs • How to maintain “Session” FacesContext.getCurrentInstance(). getExternalContext().invalidateSession() @SessionScoped @Named Class XXXBean implements Serializable { private String value = “”; : public String logout() {FacesContext.getCurrentInstance().getExt ernalContext().invalidateSession();} : public String getValue() {return value;} public void setValue(String value) { this.value = value;} } 55
  56. Clustered AP Servers Session Scoped CDI • Session Management Style

    (1) Jakarta EE Container Session Information Network Appliance or Web Server Load Balancer Jakarta EE Container Session Information AP Server #1 AP Server #2 Sticky Session Style DB DB Server Fix an AP Server for each Session 56
  57. Clustered AP Servers Jakarta EE Container Session Information Network Appliance

    or Web Server Load Balancer Jakarta EE Container Session Information AP Server #1 AP Server #2 Session Replication Style DB DB Server Fix an AP Server for each Session or/and change AP Servers in round-robin Replicate • Session Management Style (2) Session Scoped CDI 57
  58. Clustered AP Servers Session Scoped CDI • Session Management Style

    (3) Jakarta EE Container Session Information Network Appliance or Web Server Load Balancer Jakarta EE Container Session Information AP Server #1 AP Server #2 Session DB Style DB DB Server Fix an AP Server for each Session and change AP Servers in round-robin 58
  59. Session Scoped CDI • Demonstration of Sticky Session Web Server

    (Apache) Web Server (apache) Jakarta EE Container (Payara Server 5.2020.4 ) Web AP Server #1 (payara) Web AP Server #2 (payara2) DB (PostgreSQL) DB Server (postgresql) B.S. Bean (Session CDI) B.S. Bean (Session CDI) O-R Mapper (JPA) O-R Mapper (JPA) Sticky Session JPA L1 Cache JPA L1 Cache Cache JPA L2 Cache Cache JPA L2 Cache WAS Cluster (Deployment Group: demo-deployment-group) DB Server EclipseLink EclipseLink Hazelcast Hazelcast Cache Coordination Jakarta EE Container (Payara Server 5.2020.4) Load Balancer Note: (xxx) shows hostname of each server. 59
  60. Session Scoped CDI • Demonstration Environment 60 Windows 10 Home

    (1909) Oracle Virtual Box 6.1 (6.1.2) CentOS 8 (8.2.2004) Podman 2 (2.0.4) apache payara payara2 postgresql Podman Network: demo-network Host Name Podman Container
  61. Multiple tab windows • How to deal with Multiple tab

    windows Multi Windows Patterns Single Sub-Window Multiple Windows with Consistency Checks Multiple Windows with Multiple Operations Prevent from opening multiple tab windows by JavaScript Preventing from using the same session information by checking window id in session and hidden field Allow multiple tab windows operations by using View Scope or Conversation Scope instead Session Scope 61
  62. Example of View Scoped CDI • Menu Flows In the

    “Home” menu, click “Show Google Map” button.  Show the Google Map for the specified location. “Home” menu “Home” menu JSF Facelets (home.xhtml) JSF Facelets (home.xhml) 62 Exercise: Let’s modify the JSF Web Application with View Scoped CDI.
  63. Example of View Scoped CDI • JSF Control Flows Web

    Application Server (Jakarta EE Container) Presentation Layer JSF Servlet (Controller) CDI Component (ViewBean) Browser “Home” menu 2. Ajax Update 63
  64. View Scoped CDI Development • Development Procedure on Eclipse™ 1.

    Create “ViewBean.java” with @ViewScoped to provide accessors for lat, lng, zoom properties. 2. Replace the system test program named “LoginIT.java” with new one which clicks “Show Google Map” command button additionally. 3. Modify the “home.xhtml” to add a latitude, a longitude, a zoom fields and a function to show a map for the specified location using Google Map™ Web Service Component (Hint: use the <p:gmap> PrimeFaces component). 64
  65. View Scoped CDI Development • Project Explorer New Provided (New

    Version) Modify 65
  66. View Scoped CDI Development • System Test Program - LoginIT.java

    @ ExtendWith(SeleniumExtension.class) class LoginIT { @Test public void testOperations(ChromeDriver driver) throws InterruptedException{ : assertEquals("Hello World", driver.getTitle()); element = driver.findElement(By.id("showGMap")); element.click(); Thread.sleep(5000); element = driver.findElement(By.id("logout")); element.click(); Thread.sleep(5000); assertEquals(“Login Menu", driver.getTitle()); } } 66
  67. Menu Layout and Template 67

  68. Menu Layout and Template • Web Page Design Pattern –Web

    Page Layout by CSS [Fixed Layout] Whole Content (#content) Side Menu (#side) Main Part (#main) CSS Code #content { width: 1000px; float: left; … } #side { width: 200px; float: left; … } #main { width: 800px; float: left; … } 1000px 200px 800px 68
  69. Menu Layout and Template • Web Page Design Pattern –Web

    Page Layout by CSS [Floating Layout] Whole Content (#content) Side Menu (#side) Main Part (#main) CSS Code #container { width: 100%; float: left; … } #sidebar { width: 20%; float: left; … } #main { width: 80%; float: left; … } 100 % 20% 80% 69
  70. Menu Layout and Template • Web Page Design Pattern –Web

    Page Layout by CSS [Mixed Layout] Whole Content(#content) Side Menu (#side) Main Part (#main) CSS Code #content { width: 100%; float: left; … } #side { width: 200px; float: left; … } #main { width: 80%; float: left; … } 100 % 200px 80% 70
  71. Menu Layout and Template • Web Page Design Pattern –Web

    Page Layout by CSS [Responsive Layout] Whole Content (#content) Side Menu (#side) Main Part (#main) CSS Code @media screen and (min-width: 1000px) { #content { width: 1000px; … } #side { width: 200px; … } #main { margin-left: 800px; … } } @media screen and (min-width: 800px) and (max-width: 999px) { #content { width: 800px; … } #side { width: 120px; 1000px or 800px 200px or 120px 800px or 680px Screen Width >= 1000 px 800 px =< Screen Width =< 999 px 71
  72. Menu Layout and Template • JSF Facelets page with Template

    feature Header Left- Side Right- Side Footer Main <html xmlns=…> <h:head> <title>#{title}</title> </h:head> <h:body> <div id=“sidebarRight”> <ui:include src=“/rightMenu.xhtml” /> </div> <div id=“content”> <ui:insert name=“center” /> </div> Layout Template (template.xhtml) <ui:composition xmlns=… template=“/template.xhtml” > <ui:param name=“title” value=“Welcome Page” /> <ui:define name=“center”> …….. </ui:define> </ui:composition> Facelets page inserted into template (home.xhtml) CSS 72 <ui:composition xmlns=… > …….. </ui:composition> Facelets page included in template (rightMenu.xhtml)
  73. Menu Layout and Template • JSF Facelets page included by

    Template page <html xmlns=…> <h:head> <title>#{title}</title> </h:head> <h:body> <div id=“sidebarRight”> <ui:include src=“/ rightMenu.xhtml” /> </div> <div id=“content”> <ui:insert name=“center” /> </div> Layout Template (template.xhtml) <ui:composition xmlns=… template=“/template.xhtml” > <ui:param name=“title” value=“Welcome Page” /> <ui:define name=“center”> …….. </ui:define> </ui:composition> Facelets page inserted into template (home.xhtml) CSS 73 <ui:composition xmlns=… > …….. </ui:composition> Facelets page included in template (rightMenu.xhtml) <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <p:calendar id="monthlyCalendar" value="#{viewBean.calendarDate}" mode="inline" locale="en" /> </ui:composition>
  74. Menu Layout and Template • JSF Facelets page inserted by

    Template page <html xmlns=…> <h:head> <title>#{title}</title> </h:head> <h:body> <div id=“sidebarRight”> <ui:include src=“/ rightMenu.xhtml” /> </div> <div id=“content”> <ui:insert name=“center” /> </div> Layout Template (template.xhtml) <ui:composition xmlns=… template=“/template.xhtml” > <ui:param name=“title” value=“Hello World” /> <ui:define name=“center”> …….. </ui:define> </ui:composition> Facelets page inserted into template (home.xhtml) CSS 74 <ui:composition xmlns=… > …….. </ui:composition> Facelets page included in template (rightMenu.xhtml) <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" … > <ui:composition template="/template.xhtml"> <ui:param name="title" value="Hello World" /> <ui:define name="center"> …………… </ui:define> </ui:composition> </html>
  75. Menu Layout and Template • Other technics to make a

    large number of menus efficiently Efficient Patterns Reuse pages with core (JSTL) tag Switch with rendering option Switch with CSS <c:import url=“xxx.xhtml”> <h:panelGroup rendered=“#{…}”> <div ${person.personId == null ? ‘style=“display:none”’ : ‘’}> <span> ID : ${person.personId} </span> </div> 75
  76. Example of Menu Layout • Menu Layout • “Home” menu

    comprises 5 sections. Current “Home” menu JSF Facelets (home.xhml) Left- Side New “Home” menu JSF Facelets (home.xhml) Right- Side Header Footer Main Change !! 76 Exercise: Let’s modify the JSF Web Application with CSS and Template.
  77. Example of Menu Layout Development • Development Procedure on Eclipse™

    1. Revise “ViewBean.java” to add a method of “getCalendarDate()” to return the current date. 2. Replace the CSS file named “style.css” with provided new one which defines each layout section. 3. A template file named “template.xhtml” is provided as JSF layout template file. 4. New facelets files named “top.xhtml”, “leftMenu.xhtml” and “rightMenu.xhtml” are also provided to define each JSF layout section of the above template file. 5. Modify “home.xhtml” to make use of the above JSF layout template file. 77
  78. Example of Menu Layout Development • Project Explorer Modify Provided

    (New Version) Provided Provided Modify Provided Provided 78
  79. Illegal UPDATE Requests 79

  80. Illegal UPDATE Requests • How to deal with illegal UPDATE

    requests Illegal UPDATE requests By operators Re-submit after “Back” “Reload” button By malicious third parties XSS Attack CSRF Attack Cross-Site Scripting Attack Cross-Site Request Forgeries Attack After UPDATE, show the result menu again by “Reload” button. => The same UPDATE request is sent again illegally. After UPDATE, go back to previous menu by “Back” button and re-submit on recovered menu from cache. => The same UPDATE request is sent again illegally. 80 Who? How?
  81. Illegal UPDATE Requests • How to deal with illegal UPDATE

    requests [XSS Attack] 1. Access Malicious Site Target Site 2. Return including auto-redirect with malicious JavaScripts (ex. Pass URL with JavaScripts as its a query parameter.) 3. Redirected to Target Site with the JavaScripts 4. Return contents with the JavaScripts (ex. Target Site shows the query parameter.) 5. Execute the JavaScripts (ex. Execute it by rendering the query parameter) 6. Send some information like a cookie of Target Site User Attacker 81
  82. Illegal UPDATE Requests • How to deal with illegal UPDATE

    requests [CSRF Attack] 2. Access Malicious Site Target Site 3. Return with form including malicious action and input fields 4. Submit to a target site with the malicious information User 1. Login <body onload=“document.forms[0].submit()”> …. <form action=“http://xxx.com/xyz“ method=“POST”> <input type=“hidden” name=“title” value=“malicious contents” /> … <input type=“submit” /> </form> 82
  83. Illegal UPDATE Requests • Summary of Actions for illegal UPDATE

    requests Illegal Operation/ Measures Re-submit after “Back” “Reload” button XSS Attack CSRF Attack Invalidate cache on browser O Token Check O O O PRG style menu transition O Conversation Scope O O Sanitization O 83
  84. Illegal UPDATE Requests • How to deal with illegal UPDATE

    requests [Token Check] Name: Vendor: ABC Update Update Information: Name Price Vendor Notes ABC 10,100 TY Co. Confirm Update Results: Jakarta EE Container Generate Token “AB1” Request Set Token: AB1 as a hidden input field Check Token “AB1” Generate Token “XY9” Session Information “AB1” “XY9” Request with Token: AB1 Set Token: XY9 as a hidden input field Check Token “XY9” Generate Token “ZA8” Update DB Request with Token: XY9 Name Price Vendor Notes ABC 10,100 TY Co. 84 “ZA8”
  85. Illegal UPDATE Requests • How to deal with illegal UPDATE

    requests [Sanitization] Escape special characters in JavaScript like the followings. Original Character Converted Character < &lt; > &gt; “ &quot; & &amp; For JSP (There are 2 ways) For JSF (Nothing to do) 1. <c:out value=“${param_n}” escapeXml=“true” /> Sanitization is automatically done by default 2. <@ tablib url=“http://java.sun.com/jsp/jstl/functions” prefix=“fn” %> ${fn:escapeXml(param_n)} How to escape the above special characters: 85
  86. Other Topics 86

  87. PrimeFaces™ JSF Components • PrimeFaces™ for JSF (Rich Open Source

    JSF Components) 87
  88. Exercise 88

  89. Exercise for Token Check • Token Flow  “Login” generates

    a new Token and set it to HTTP Session and initialize Hidden Field of next menu using the Token in HTTP Session.  “Show Google Map” check the Token between HTTP Session and Hidden Field and if OK, it generates another new Token and set it to HTTP Session and Hidden Field. “Home” menu JSF Facelets (home.xhml) “Login” menu JSF Facelets (login.xhtml) Generate new Token “AB1” Check Token “AB1” HTTP Session “AB1” “AB1” Hidden Field Generate new Token “XJ8” 89 Initialize “AB1”