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

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

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

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 requires the basic skills of Windows 10, Rocky Linux, 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 Rocky Linux.

Koichi NAKAGAWA

November 26, 2020
Tweet

More Decks by Koichi NAKAGAWA

Other Decks in Programming

Transcript

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

    Jakarta EE specification Rich Component Based MVC Framework 1 By Koichi NAKAGAWA Enterprise Web Application Development Course (4)
  2. Update Information • Ver. 3: Use Rocky Linux™ instead of

    CentOS™ as a Linux platform and Payara Server 6™ certified as Jakarta EE 9.1 Platform Compatible Products. • Ver. 2 : Use JDK 11 instead of JDK 8 and Jakarta EE 9 instead of Jakarta EE 8 in all exercises. 2
  3. EWA development course curriculum 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 (Rocky Linux™) Total EWA Development Exercise Jakarta Batch Java SE (Oracle JDK™/OpenJDK™) Required Skills to take courses Test Tool with JUnit5 PostgreSQL™ Administration 4 Object Oriented Development Methodology
  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. 5
  5. Assumption for this course • The trainees who take this

    course are required the following skills in advance • Payara Server (Version: 6.2021.1.Alpha1) – Basic Administration Operations • Oracle JDK/OpenJDK (Version: 11) • Eclipse IDE for Enterprise Java Developers (Version: 2021-12 (4.22.0)) • Build Tool Training Course • Version Control Tool Training Course • Test Tool Training Course 6
  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 7
  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 8
  8. 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 10
  9. 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 11
  10. 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 12 Template (Facelets)
  11. 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 13
  12. 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 14
  13. 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 15
  14. 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 16
  15. 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 17
  16. 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 18
  17. 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) 19
  18. 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 20
  19. 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 21
  20. 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 22 Forward
  21. 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 23
  22. 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 24
  23. 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 25
  24. 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? 26
  25. 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 27
  26. 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 28 Fail !!!
  27. 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 29 Directory File
  28. Web Configuration • web.xml (1) <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0"> <display-name>JSF Demo System</display-name> <description> This JSF demo program demonstrates the JSF. </description> <context-param> <param-name>jakarta.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) 30
  29. Web Configuration • web.xml (2) <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>jakarta.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 31
  30. 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”) 32
  31. 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 33
  32. 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 34
  33. 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) 35
  34. First JSF Web Application Exercise • 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) 37 Exercise: Let’s make the First JSF Web Application.
  35. First JSF Web Application Exercise • 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 38
  36. First JSF Web Application Exercise • 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 from the folders of “src/main/java” and “src/test/java” and put a package of “org.example.jsfproject” into each of the folders. 4. Change the value of <url-pattern> in <servlet-mapping> for <servlet-name> of “Faces Servlet” to “/faces/*” and the value for <welcome-file> should be “faces/login.xhtml” in “WEB-INF/web.xml”. 5. Change the schema declaration in “WEB-INF/faces-config.xml” into the following declaration. 39 <faces-config 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-facesconfig_3_0.xsd" version="2.3"> </faces-config>
  37. First JSF Web Application Exercise • Development Procedure on Eclipse™

    6. Rename the value of <artifactId> to “jsfproject”, the value of <name> to “${project.artifactId}” and add a <dependency> with “org.seleniumhq.selenium” as <groupId>, “selenium-support” as <artifactId>, “4.1.0” as <version> and “test” as <scope> and add another <dependency> with “org.primefaces” as <groupId>, “primefaces” as <artifactId>, “10.0.0” as <version> in “pom.xml” . 7. Add a provided unit test program named “AuthBeanTest.java” and add another provided system test program named “LoginIT.java” under “org.example.jsfproject”. 8. Make RequestScoped Named CDI “AuthBean.java” under “org.example.jsfproject” which has String properties of “userId” and “password” and their accessors and a method of “login” to pass the above 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. 10. Build war package with Maven and check the result of unit and system tests. 40
  38. First JSF Web Application Exercise • 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); } } 42
  39. First JSF Web Application Exercise • System Test Program -

    LoginIT.java package org.example.jsfproject; import java.time.Duration; 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.SeleniumJupiter; @ ExtendWith(SeleniumJupiter.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, Duration.ofSeconds(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(5000); } } 43
  40. 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. 45
  41. 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 … … 46 Access View Scoped CDI “action” method returns String value to change view
  42. 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) 47
  43. 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) 48
  44. 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) 49
  45. 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) 50
  46. 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 51
  47. 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) 52 Exercise: Let’s modify the JSF Web Application with Session Scoped CDI.
  48. 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 53
  49. Session Scoped CDI Development • Development Procedure on Eclipse™ 1.

    Revise “AuthBean.java” to specify @SessionScoped instead of @RequestScoped, 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. 54
  50. 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); } } 56
  51. 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;} } 57
  52. 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 58
  53. 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 59
  54. 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 60
  55. Session Scoped CDI • Demonstration of Sticky Session Style Web

    Server (Apache 2.4.37-39) Web Server (apache) Jakarta EE Container (Payara Server 6.2021.1.Alpha1) Web AP Server #1 (payara) Web AP Server #2 (payara2) DB (PostgreSQL 13.3-1) 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 Load Balancer Note: (xxx) shows hostname of each server. 61 Jakarta EE Container (Payara Server 6.2021.1.Alpha1)
  56. Session Scoped CDI • Demonstration Environment 62 Windows 10 Home

    (21H2) Vmware Workstation 16 Player 16.2.1 Rocky Linux 8.5 Podman 3.3.1-9 apache payara payara2 postgresql Podman Network: demo-network Host Name Podman container
  57. 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 63
  58. View Scoped CDI Exercise • 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) 64 Exercise: Let’s modify the JSF Web Application with View Scoped CDI.
  59. View Scoped CDI Exercise • JSF Control Flows Web Application

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

    Create “ViewBean.java” with “@ViewScoped” and “@Named” under “org.example.jsfproject” package to provide accessors for “lat”, “lng” as float properties and “zoom” as int property and implements “java.io.Serializable” interface. 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). 66
  61. View Scoped CDI Development • System Test Program - LoginIT.java

    (extracted) @ ExtendWith(SeleniumExtension.class) class LoginIT { @Test public void testOperations(ChromeDriver driver) throws InterruptedException{ : assertEquals("Hello World", driver.getTitle()); Thread.sleep(5000); element = driver.findElement(By.id("showGMap")); element.click(); Thread.sleep(5000); elemelement = driver.findElement(By.id("logout")); element.click(); : } } 68
  62. 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 70
  63. 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% 71
  64. 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% 72
  65. 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 73
  66. 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 74 <ui:composition xmlns=… > …….. </ui:composition> Facelets page included in template (rightMenu.xhtml)
  67. 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 75 <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>
  68. 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 76 <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>
  69. Menu Layout and Template • Other technics to manage 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> 77
  70. Menu Layout Exercise • 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 !! 78 Exercise: Let’s modify the JSF Web Application with CSS and Template.
  71. Menu Layout Exercise • Development Procedure on Eclipse™ 1. Revise

    “ViewBean.java” to add a method of “getCalendarDate()” to return the current date as “Date” object. 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. 79
  72. Menu Layout Exercise • Project Explorer Modify Provided (New Version)

    Provided Provided Modify Provided Provided 80
  73. 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. 82 Who? How?
  74. 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 83
  75. Illegal UPDATE Requests • How to deal with illegal UPDATE

    requests [CSRF Attack] 2. Access Malicious Site Target Site 3. Return with a form including a malicious action and some hidden 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> 84
  76. 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 85
  77. 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. 86 “ZA8”
  78. 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: 87
  79. 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” 91 Initialize “AB1”