Slide 1

Slide 1 text

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)

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

Jakarta Server Faces Jakarta Server Faces (JSF) with CDI 3

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

Jakarta Server Faces (JSF) with Jakarta Contexts and Dependency Injection (CDI) Basics 9

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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)

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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) : : : : CDI Component (“authBean”) JSF Facelets (“index.xhtml”) JSF Facelets (“home.xhtml”) Hello !!! Browser 16

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

JSF Control Flows and View Navigation • JSF Customized View Navigation : : home /homeMenu.xhtml : : : login /loginMenu.xhtml : 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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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: Model(CDI): @Named public class XyzBean { : public String funcA() { : return “nextMenu”;} : } Current Menu Next Menu 21

Slide 22

Slide 22 text

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: Model(CDI): @Named public class XyzBean { : public String funcA() { : return “nextMenu?faces- redirect=true”;} : } Current Menu Next Menu 22 Forward

Slide 23

Slide 23 text

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: View(Facelets) Next Menu: Model(CDI): @Named public class XyzBean { : public String funcA() { : return;} : } Current Menu Next Menu 23

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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 : : : : : : : JSF Facelets (“index.xhtml”) 2. Update (Redraw) Browser 28 Fail !!!

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

Web Configuration • web.xml (1) JSF Demo System This JSF demo program demonstrates the JSF. jakarta.faces.PROJECT_STAGE Development Control if the messages are displayed or not. (Default: Development) 30

Slide 31

Slide 31 text

Web Configuration • web.xml (2) Faces Servlet jakarta.faces.webapp.FacesServlet 1 Faces Servlet /faces/* 30 faces/login.xhtml Define “Servlet Name” for JSF Controller “Servlet Class” Map “URL Pattern” to “Servlet Name” for JSF Controller 31

Slide 32

Slide 32 text

JSF Facelets • Sample JSF Facelets Basics Login Menu JSF Facelets (“login.xhtml”) 32

Slide 33

Slide 33 text

JSF Facelets • Facelets Basics – Definitions For JSF Standard tags For Primefaces™ tags For JSTL tags 33

Slide 34

Slide 34 text

JSF Facelets • Facelets Basics – HTML Header Login Menu Set “Content-Type” Set Title 34

Slide 35

Slide 35 text

JSF Facelets • Facelets Basics – HTML Body CDI Component (AuthBean) 35

Slide 36

Slide 36 text

First JSF Web Application 36

Slide 37

Slide 37 text

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.

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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 in for of “Faces Servlet” to “/faces/*” and the value for 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

Slide 40

Slide 40 text

First JSF Web Application Exercise • Development Procedure on Eclipse™ 6. Rename the value of to “jsfproject”, the value of to “${project.artifactId}” and add a with “org.seleniumhq.selenium” as , “selenium-support” as , “4.1.0” as and “test” as and add another with “org.primefaces” as , “primefaces” as , “10.0.0” as 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

Slide 41

Slide 41 text

First JSF Web Application Exercise • Project Explorer New New New Provided Provided Modify 41

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

CDI Scopes 44

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

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.

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

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 inside a new tag. 3. Replace the system test program named “LoginIT.java” with new one which clicks “Logout” link additionally. 54

Slide 55

Slide 55 text

Session Scoped CDI Development • Project Explorer Modify Modify Provided (New Version) 55

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

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

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

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

Slide 61

Slide 61 text

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)

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

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.

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

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 PrimeFaces component). 66

Slide 67

Slide 67 text

View Scoped CDI Development • Project Explorer New Provided (New Version) Modify 67

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

Menu Layout and Template 69

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

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

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

Menu Layout and Template • JSF Facelets page with Template feature Header Left- Side Right- Side Footer Main #{title}
Layout Template (template.xhtml) …….. Facelets page inserted into template (home.xhtml) CSS 74 …….. Facelets page included in template (rightMenu.xhtml)

Slide 75

Slide 75 text

Menu Layout and Template • JSF Facelets page included by Template page #{title}
Layout Template (template.xhtml) …….. Facelets page inserted into template (home.xhtml) CSS 75 …….. Facelets page included in template (rightMenu.xhtml)

Slide 76

Slide 76 text

Menu Layout and Template • JSF Facelets page inserted by Template page #{title}
Layout Template (template.xhtml) …….. Facelets page inserted into template (home.xhtml) CSS 76 …….. Facelets page included in template (rightMenu.xhtml) ……………

Slide 77

Slide 77 text

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
ID : ${person.personId}
77

Slide 78

Slide 78 text

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.

Slide 79

Slide 79 text

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

Slide 80

Slide 80 text

Menu Layout Exercise • Project Explorer Modify Provided (New Version) Provided Provided Modify Provided Provided 80

Slide 81

Slide 81 text

Illegal UPDATE Requests 81

Slide 82

Slide 82 text

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?

Slide 83

Slide 83 text

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

Slide 84

Slide 84 text

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 …. … 84

Slide 85

Slide 85 text

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

Slide 86

Slide 86 text

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”

Slide 87

Slide 87 text

Illegal UPDATE Requests • How to deal with illegal UPDATE requests [Sanitization] Escape special characters in JavaScript like the followings. Original Character Converted Character < < > > “ " & & For JSP (There are 2 ways) For JSF (Nothing to do) 1. 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

Slide 88

Slide 88 text

Other Topics 88

Slide 89

Slide 89 text

PrimeFaces™ JSF Components • PrimeFaces™ for JSF (Rich Open Source JSF Components) 89

Slide 90

Slide 90 text

Exercise 90

Slide 91

Slide 91 text

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”