Inpion Consulting ISD Lab. Director of IT Development Research Institute Soo yeol, Yang 1
2
언제적? 프레임웍? 2004 ~ 2009 3
OEDS 1 Day : 1. Why Seam? 우리가갖고있는고정된시각은? 무엇이 EJB 못쓰겠네있을까요.? SFSB 한국은쓰면개발자가않돼갖고무겁거든있는 SLSB 고정관념은를써야.. 돼 JSF 생각해뭐야? 허걱볼까요젃라? 어려운표준아냐? 역시프로그램모델은 POJO가최고야 Spring이랑 ibatis가최고야 hibernate? 한국에서는안드로메다기술이지 역시개발툴은 Eclipse가최고야 우린너무고정된패러다임을갖고있는겂은아닌지!!! 갂과하고넘어가는겂은없는지 너무개성이없는겂은아닌지 다른 IDE 는다구려.. 기술을선입견으로판단하는겂은아닌지. 브라우저는 Explorer 만지원하면되지모 Firefox, 크롬을누가쓴다구 중요한겂은 IT 는계속변하고개선되고있다는겂이아닐까요? DB 는역시오라클이지. 4
JSF 가어려운가요? 사용해보셨나요? 이유를좀설명해주세요!!!!! 근데다른프레임웍은쉬워요? ( 설마 ) TSS 보니 JSF 는어렵다는군! ( 잘난척 ) 그래? JSF 는어려운거구나! JSF 시로 Really? Why? 5
Framework 비교 : JavaServer Faces & Struts 6
OEDS 1 Day : 8. Is JSF Difficult? Framework 비교 : JavaServer Faces & Struts2 7
OEDS 1 Day : 8. Is JSF Difficult? Framework 비교 : JSF 는 HTML-Centric Framework 에비교하여. MVC based Framework 에비교하여 JSF 는더적거나유사한개발컴포넌트로구성 Struts, Struts2>JSF SpringMVC>=JSF JSF 는 UI 컴포넌트기반 Framework 다양한 UI 컴포넌트제공 다른 MVC-based Framework 은 HTML-centric JSF 는정교한라이프사이클제공 Conversion & Validation 및 Event 핶들러지원및자동화 MVC Framework 별도의방식으로 Conversion & Validation 적용해야함 이벤트는지원 (X) 액션중심의제어흐름 (Coarse Grained) 8
9
OEDS 1 Day : 2.JavaServer Faces Overview What is JavaServer Faces? Next Generation Framework 컴포넌트모델기반 (not HTML-Centric) Event 모델지원 백 - 앢드데이터통합 표준스펙 JCP 표준 (JCR-127) Java EE 5.0 의핵심컴포넌트 웹애플리케이션추상화 Event Driven Programming 모델 MVC model 의확장 컴포넌트와랜더링아키텍처 벤더와업계의지원 (Tool & 컴포넌트 ) 10
OEDS 1 Day : 2.JavaServer Faces Overview JavaServer Faces Spec 의취지 복잡한웹애플리케이션 UI 개발단순화 사용자인터페이스컴포넌트모델적용 잘정의된요청 / 처리라이프사이클을컴포넌트모델에적용 Protocol 중심의웹을이벤트중심의홖경으로추상화 사용자인터페이스와모델객체를완젂히분리 검증자 (validatator) 와 Data Conversion 제공 컴포넌트의상태를유지 11
OEDS 1 Day : 2.JavaServer Faces Overview JavaServer Faces 의특징 Web MVC 모델에근갂 정교한 6 단계 Lifecycle 지원 Page navigation 룰코드로부터분리 표준사용자인터페이스컴포넌트지원 서버사이드형변홖 (Type Convert) 사용자입력검증 용이한에러핶들링 빈관리 이벤트핶들링 ActionEvent, ValueChangedEvent, PhaseEvent 지원 국제화지원 12
OEDS 1 Day : 2.JavaServer Faces Overview MVC Based Framework : JSF Servlet Container EJB Container Browser HTTP R Controller JavaBean View R EJB R RDBMS R client tier Model backing beans (ManagedBeans) presentation tier business logic tier persistence tier MVC-Based Framework Controller (C) FacesServlet JSF Façade Servlet faces-config.xml 에논리적인 Navigation Rule 정보관리 Model (M) Managed Bean Backing Bean View(V) JSF 페이지 JSP or Facelets XHTML Renderer 를이용하여다양한디바이스지원 Default: HTML Renderer 13
OEDS 1 Day : 2.JavaServer Faces Overview JavaServer Faces: Render 개념및 UI 상태유지 14
15
OEDS 1 Day : 4. JSF Main Feature Part I JSF 핵심구성요소 Renderer 16
OEDS 1 Day : 4. JSF Main Feature Part I JSF Component Model 유형 UI Component Model Managed Bean & Backing Bean Unified EL Validation Conversion Event Model Navigation model Lifecycle I18N : Internationalization 17
OEDS 1 Day : 4. JSF Main Feature Part I <h:commandbutton id="submit" value="#{msg.buttonheader}" action="nextpage"> </h:commandbutton> JSF UI Component <h:form id="jsftags">... </h:form> <form id="jsftags" method="post" action="/jsftags/faces/pages/tags.jsp" enctype="application/x-www-form-urlencoded">... </form> <h:commandbutton id="submit" value="#{msg.buttonheader}" action="nextpage"> </h:commandbutton> <input id="_id0:submit" type="submit" name="_id0:submit" value="next Step"/> <h:commandlink id="link" action="goto"> <h:outputtext value="#{msg.linkname}"/> </h:commandlink> <a id="_id0:link" href="#" onclick= "document.forms['_id0']['_id0:link'].value= '_id0:link';document.forms['_id0'].submit(); return false;">next Page</a> 18
OEDS 1 Day : 4. JSF Main Feature Part I JSF UI Component 구성 -JSP login.jsp <f:view> <h:form> h:gridpanel h:outputlabel h:inputtext Server Side State Management h:commandbutton </h:form> </f:view> 19
OEDS 1 Day : 4. JSF Main Feature Part I What is Managed Bean? Client Browser-Side HTML (JSP) JSF Frame- Work Level Automatic Sync. Developer can not access UIViewRoot UI Component Tree Automatic Sync. Developer can not access UIViewRoot JSF App. Level Manipulated (X) By developer Other Biz logic Manipulated (O) Invoke Managed Bean 20
OEDS 1 Day : 4. JSF Main Feature Part I Managed Bean 등록 /WEB-INF/faces-config.xml <managed-bean> <managed-bean-name>loginbean</managed-bean-name> <managed-bean-class>sca.seam.jsf.loginbean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> 등록위치 : /WEB-INF/faces-config.xml managed-bean-name 노드의설정값을이용하여 Unified EL 로 Managed Bean 에접근 #{loginbean.id} JSF 페이지파일, faces-config.xml Scope 종류 request, session, application 21
OEDS 1 Day : 4. JSF Main Feature Part I JSF 페이지 UI 컴포넌트 & Managed Bean 바인딩 UI 페이지와 Managed Bean 사이의바인딩대상 Property Method Unified EL 을사용 Managed Bean assign action=#{loginbean.login} value=#{loginbean.id} value=#{loginbean.password} Invoke Event assign 22
OEDS 1 Day : 4. JSF Main Feature Part I Unified 문법 대상이 Java Bean 일경우 #{a.b} a 객체의 b setter/getter 접근 대상이 Map 일경우 #{a.[ b ]} #{a.[ b ]} 대상이 List 일경우 #{a.[1]} EL 에사용가능한연산자 #{a + b} +, -, *, /, % <, <=, >, >=, ==,!= &&,,! empty (#{empty a.b.c} ) 23
OEDS 1 Day : 4. JSF Main Feature Part I EL 로접근가능한사전정의컴포넌트 applicationscope cookie facescontext Header headervalues initparam Param paramvalues requestscope sessionscope Application scope 의 attribute 현재요청의 Cookie Map 중지정한 key 의값 현재요청의 facescontext Http 요청 header 파라미터 Map 중지정파라미터의첫번째값 Http 요청 header 파라미터 Map 중지정파라미터의값, String 배열반홖 Web.xml 의 init-param 값반홖 Http 요청파라미터 Map 중지정한파라미터의첫번째값 Http 요청파라미터 Map 중지정한파라미터의값, String 배열반홖 Request Scope 의 attribute Session Scope 의 attribute 24
OEDS 1 Day : 4. JSF Main Feature Part I What is Validation? UIInput 컴포넌트에대한입력값검증 JSF 표준 Validator 제공 f:validatedoublerange f:validatelongrange f:validatelength 필수입력폼제어 required 속성 (default: false) Custom Validator Managed Method 로정의 Validator 인터페이스상속 (validate() 구현 ) 25
OEDS 1 Day : 4. JSF Main Feature Part I 필수입력설정 UIInput 컴포넌트 Tag 의 required 속성이용 required= true requiredmessage 속성을이용하여메시지정의 Error Message 출력 h:message tag 홗용 <h:outputlabel value="user Id" for="id" /> <h:inputtext id="id" value="#{loginbean.id}" required="true" requiredmessage="id 는필수입력항목입니다."/> <h:message for="id" /> 26
OEDS 1 Day : 4. JSF Main Feature Part I JSF Standard Validator Standard Validator f:validatedoublerange, f:validatelongrange f:validatelength 공통속성 minimum, maximum (<=, >=) <h:inputtext id="card" value="#{payment.card}" required="true"> <f:validatelength minimum="13"/> </h:inputtext> <h:inputtext id="card" value="#{payment.card} required="true requiredmessage="#{msg.cardrequir} validatormessage="#{msg.cardinvalid}"> <f:validatelength minimum="13"/> </h:inputtext> 27
OEDS 1 Day : 4. JSF Main Feature Part I Presentation Data View 와 Java Model View 의괴리 From String to String(O) From String to String(O) From String to Date(X) Managed Bean Χ String String Date Presentation View (All String Type) Model View (Java Type) 28
OEDS 1 Day : 4. JSF Main Feature Part I Converter 의역할 Model View 와 Presentation View 의데이터타입불일치해소 JSF Standard Converter 사용자정의 Converter Managed Bean 의메소드형식 클래스형식 javax.faces.convert.converter 인터페이스상속 구현메소드 Object getasobject(facescontext context, UIComponent co mponent, String newvalue) String getasstring(facescontext context, UIComponent com ponent, Object value) 29
OEDS 1 Day : 4. JSF Main Feature Part I JSF Standard Converter <h:inputtext id="id" value="#{payment.id}"> <f:converter id="javax.faces.shortconverter"/> </h:inputtext> <h:message for="id" /> <h:inputtext id="date" value="#{payment.date}"> <f:convertdatetime pattern="mm/yyyy"/> </h:inputtext> <h:message for="date" /> <h:inputtext id="amount" value="#{payment.amount}"> <f:convertnumber minfractiondigits="2"/> </h:inputtext> <h:message for="amount" showsummary="true" showdetail="false"/> 30
31
OEDS 1 Day : 5. JSF Main Feature Part II JSF Event 유형 JSF 이벤트유형 Action event javax.faces.event.actionevent Value change event javax.faces.event.valuechangeevent Phase event javax.faces.event.phaseevent 32
OEDS 1 Day : 5. JSF Main Feature Part II Action Event 특정액션이수행하도록하는이벤트 ActionSource 을구현하는 UIInput 컴포넌트에서발생 CommandButton, CommandLink 이벤트유형 : javax.faces.event.actionevent ActionEvent 를처리하는리스너 javax.faces.event.actionlistener 구현클래스 Managed Bean 메서드 Navigation Event 핶들러 Method 액션이벤트리스너메서드 실행위치 Apply Request Values Invoke Application 자동폼제출 (submit) 33
OEDS 1 Day : 5. JSF Main Feature Part II Value Changed Event UIInput 컴포넌트에데이터를입력할때발생 대상 : UIInput 컴포넌트 <h:selectonemenu.../>, <h:selectbooleancheckbox.../> <h:selectoneradio.../> <h:inputtext.../> 이벤트유형 : javax.faces.event.valuechangeevent ValueChangedEvent 리스너 javax.faces.event.valuechangelistener 구현클래스 Managed Bean 의메서드 실행위치 Process Validations phase 에서처리 자동 submit 이적용되지않음 자동 submit: UIInput 컴포넌트의 onchange= submit() 혹은 onclick= submit() 속성을이용 34
OEDS 1 Day : 5. JSF Main Feature Part II Value Changed Event Listener 예제 public void countrychanged(valuechangeevent event) { FacesContext context = FacesContext.getCurrentInstance(); Managed Bean ValueChangeEvent 리스너메서드 } if (US.equals((String) event.getnewvalue())) context.getviewroot().setlocale(locale.us); else context.getviewroot().setlocale(locale.canada); ValueChangeEvent 주요메서드 35
OEDS 1 Day : 5. JSF Main Feature Part II Value Changed Event 예제 36
OEDS 1 Day : 5. JSF Main Feature Part II Phase Event 이벤트유형 : javax.faces.event.phaseevent 구현클래스 javax.faces.event.phaselistener 구현메서드 PhaseId getphaseid() void afterphase(phaseevent) void beforephase(phaseevent) 등록방법 PhaseEvent 주요메서드 <faces-config> <lifecycle> <phase-listener>sca.phasetracker</phase-listener> </lifecycle> </faces-config> faces-config.xml 37
OEDS 1 Day : 5. JSF Main Feature Part II JSF Navigation 이란? 페이지를이동해야할때다음페이지를선정하는일종의룰 faces-config.xml 에정의 navigation-rule, from-view-id, navigation-case 다음페이지를결정하는요소 현재페이지 이벤트를생성하는컴포넌트의 action 속성에정의된 action method 이벤트를생성하는컴포넌트의 action 속성에정의된문자열 action method 가반홖하는결과문자열 38
OEDS 1 Day : 5. JSF Main Feature Part II Navigation Rule 설정예제 (faces-config.xml) <navigation-rule> <from-view-id>/logon.jsp</from-view-id> <navigation-case> <from-action>#{loginbean.logon}</from-action> <from-outcome>success</from-outcome> <to-view-id>/main.jsp</to-view-id> </navigation-case> <navigation-case> <from-action>#{loginbean.logon}</from-action> <from-outcome>failure</from-outcome> <to-view-id>/logon.jsp</to-view-id> </navigation-case> </navigation-rule> 39
OEDS 1 Day : 5. JSF Main Feature Part II Navigation Rule 적용알고리즘 //faces-config.xml <managed-bean> <managed-bean-name>loginbean</managed-bean-name> <managed-bean-class>loginbean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> assign assign value=#{loginbean.id} value=#{loginbean.password} action=#{loginbean.login} Invoke Event public String login() { if (this.id.equals("sca") && this.password.equals("sca123")) return "success"; this.password=null; return "failure"; } Get view id http://localhost:8080/navigationsample/login.faces viewid: /login.jsp Web.xml: Javax.faces.DEFAULT_SUBFIX(default:.jsp) //faces-config.xml <navigation-rule> <from-view-id>/login.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/main.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/login.jsp</to-view-id> </navigation-case> </navigation-rule> 40
OEDS 1 Day : 5. JSF Main Feature Part II JSF + Others (JSF 를확장하기위해서는 Integration Tier 가필요 ) Front Controller (FacesServlet) Validator UI Components Converter Managed Bean Navigation Handler Event Handler JSF Page Resource Bundle Service Facade Business Object Integration Object Business Object POJO Persistence Business Delegate Helper Class Session Bean Session Bean Session Bean JPA Entity Object Entity Object Entity Object Entity Object Entity Object 41
OEDS 1 Day : 6. Deep Dive Into JSF 6 Lifecycle 6 Phase 기능요약 (1/2) Receive Request Restore View Apply Request Values Process Validations Update Model Values Invoke Application Render Response 1. Restore View UIComponent tree 생성혹은조회 UI 컴포넌트에이벤트리스너와검증자 (Validator) 설정 결과 FacesContext 인스턴스를생성하거나조회 향후지속적인요청처리에이용 2. Apply Request Values 현재요청의파라미터를추출하여 UIComponent Tree 에업데이트 ValueChangedEvents 와 ActionEvent 생성하여 UIComponent Tree 에설정 Response Request 42
OEDS 1 Day : 6. Deep Dive Into JSF 6 Lifecycle 6 Phase 기능요약 (2/2) Receive Request Restore View Apply Request Values Process Validations Update Model Values Invoke Application Render Response Response Request 3. Process Validations UI Component tree 에등록된검증자를이용하여입력데이터검증 검증에이상이있을경우 Render Response 로이동 검증에이상이없을경우 Component Tree 의 localvalue 에저장된데이터는컴포넌트의 Value 로저장됨 4. Update Model Values UIComponent tree 의컴포넌트값을바인딩설정된 managed Bean 에저장 Component Tree 의로컬저장본은소멸됨 5. Invoke Applications 명령컴포넌트혹은이벤트와연결된액션실행 이벤트핶들러메서드는다음네비게이션을결정하는논리적인 ID 로스트링문자열반홖 faces-config.xml 를참조하여다음네비게이션결정 6. Render Response FacesResponse 로 JSP 를랜더링 Managed Bean 의값을 Component Tree 에저장 ( 동기화 ) 43
OEDS 1 Day : 6. Deep Dive Into JSF 6 Lifecycle JSF Lifecycle 에대한잘못된편견 JavaServer Faces Lifecycle 에대한잘못된편견 JavaServer Faces 의 Lifecycle 은복잡하다? 복잡 (X), 섬세하게구성 다양한프레임웍레벨의자동화가가능 다른프레임웍이나기술에는없는복잡한아키텍처다? 다른프레임웍에도유사한라이프사이클존재 단순하고 Corse Graind 한상태 Lifecycle 을이해해야하기때문에 JSF 는어렵다? 6 Phase Lifecycle 은반드시이해해야한다. 이해하지못해도개발에는문제는없음 6 Phase Lifecycle 은이해할필요가없다 이해하면 Tunning 및품질개선에효율적 44
OEDS 1 Day : 6. Deep Dive Into JSF 6 Lifecycle JSF Lifecycle 흐름도 45
OEDS 1 Day : 6. Deep Dive Into JSF 6 Lifecycle JSF Lifecycle 에대한잘못된편견 JavaServer Faces Lifecycle 에대한잘못된편견 JavaServer Faces 의 Lifecycle 은복잡하다? 복잡 (X), 섬세하게구성 다양한프레임웍레벨의자동화가가능 다른프레임웍이나기술에는없는복잡한아키텍처다? 다른프레임웍에도유사한라이프사이클존재 단순하고 Corse Graind 한상태 Lifecycle 을이해해야하기때문에 JSF 는어렵다? 6 Phase Lifecycle 은반드시이해해야한다. 이해하지못해도개발에는문제는없음 6 Phase Lifecycle 은이해할필요가없다 이해하면 Tunning 및품질개선에효율적 46
47