› attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun...

69
<SCWCD Note> 1. Primary Source(허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf ? Michelle : WCDStudyNotes- Michelle.pdf ? Velmurugan Periasamy : SCWCD Study Notes.doc ? Miftah Khan : jsp_study_guide.rtf (JSP 1.1 Spec) ? Miftah Khan : se rvlet_study_guide.rtf (Servlet 2.3 Spec) ? 손수정 : sccd6 - dtd.hwp 2. Secondary Source ? http://java.sun.com/dtd/web - app_2_3.dtd ? http://java.sun .com/dtd/web- jsptaglibrary_1_2.dtd ? jsp_1_2_fcs_spec.pdf ? servlet_2_3_fcs_spec.pdf 3. Mock Exam. ? javaranch.com ( http://www.javaranch.com/carl/scwcd/scwcd_mock_logo.jsp ) ? Eduardo Cobian's SCWCD Test ( http://www.javaranch.com/carl/SCWCD.htm ) ? Mika Hirvasoja's Mock Exam ( http://www.withmilk.com/scwcd.jsp ) ? Anand Chawla's Mock Exam ( http://www.podar.net/scwcd/ ) 4. About Note ? 이론과 DD(De ployment Descriptor) 구성을 붙였음. ? 이해하기 쉽도록 단원 및 내용의 순서 변경. ? 별도의 단원으로 되어 있는 내용으로 중복된 것은 삭제. ? 맨 마지막엔 목차를 한 번 쭉 읽어보는게 도움이 될 겁니다… by 강 영 오 [email protected]

Transcript of › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun...

Page 1: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<SCWCD Note>

1. Primary Source (허가받은 적 없음…)

? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? Michelle : WCDStudyNotes-Michelle.pdf

? Velmurugan Periasamy : SCWCD Study Notes.doc

? Miftah Khan : jsp_study_guide.rtf (JSP 1.1 Spec)

? Miftah Khan : servlet_study_guide.rtf (Servlet 2.3 Spec)

? 손수정 : sccd6-dtd.hwp

2. Secondary Source

? http://java.sun.com/dtd/web-app_2_3.dtd

? http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd

? jsp_1_2_fcs_spec.pdf

? servlet_2_3_fcs_spec.pdf

3. Mock Exam.

? javaranch.com (http://www.javaranch.com/carl/scwcd/scwcd_mock_logo.jsp)

? Eduardo Cobian's SCWCD Test (http://www.javaranch.com/carl/SCWCD.htm)

? Mika Hirvasoja's Mock Exam (http://www.withmilk.com/scwcd.jsp)

? Anand Chawla's Mock Exam (http://www.podar.net/scwcd/ )

4. About Note

? 이론과 DD(Deployment Descriptor) 구성을 붙였음.

? 이해하기 쉽도록 단원 및 내용의 순서 변경.

? 별도의 단원으로 되어 있는 내용으로 중복된 것은 삭제.

? 맨 마지막엔 목차를 한 번 쭉 읽어보는게 도움이 될 겁니다…

by 강 영 오

[email protected]

Page 2: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

< 목 차 >

제 1 장. Servlets. _______________________________________________________________ 5

1 Servlet Model. ______________________________________________________________ 5

1.1 Http Method : HttpServlet abstract class. _______________________________________________ 5

1.2 Http Method 특징 . _________________________________________________________________ 5

1.3 Parameter, Header. _________________________________________________________________ 5

1.4 Response _________________________________________________________________________ 6

1.5 Redirect __________________________________________________________________________ 6

1.6 Three Web Scopes : Request, Session, Context ___________________________________________ 6

1.7 Life-Cycle : Servlet interface. _________________________________________________________ 8

1.8 RequestDispatcher : Include / Forward._________________________________________________ 8

2 Servlet Container Model.______________________________________________________11

2.1 Servlet Context Init Parameter : <context-param> _______________________________________ 11

2.2 Listener : <listener> _______________________________________________________________ 11

2.3 Distributable Application. ___________________________________________________________ 12

3 Structure & Deployment._____________________________________________________ 13

3.1 Application Structure ______________________________________________________________ 13

3.2 <servlet>, <servlet-mapping> ________________________________________________________ 13

4 Session Management. _______________________________________________________ 15

4.1 Session __________________________________________________________________________ 15

4.2 Session Invalidating : <session-config>_________________________________________________ 15

4.3 Session Tracking.__________________________________________________________________ 15

5 Server-Side Exception. ______________________________________________________ 17

5.1 Error Page. ______________________________________________________________________ 17

5.2 <error-page> _____________________________________________________________________ 17

5.3 sendError, setStatus _______________________________________________________________ 18

5.4 log. _____________________________________________________________________________ 18

6 Security. _________________________________________________________________ 19

6.1 보안 용어 ._______________________________________________________________________ 19

6.2 <security-role-ref>, <security-constraint>, <security-role>_________________________________ 19

6.3 Authentication Type : BASIC, DIGEST, CLIENT-CERT, FORM ___________________________ 21

6.4 <login-config> ____________________________________________________________________ 23

7 Thread-safe Servlets.________________________________________________________ 24

제 2 장. JSPs._________________________________________________________________ 26

8 The JSP Model ____________________________________________________________ 26

Page 3: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

8.1 JSP Tag Syntax ___________________________________________________________________ 26

8.2 JSP Tag 특성_____________________________________________________________________ 26

8.3 page Directive ____________________________________________________________________ 26

8.4 Equivalent XML-based Tag. _________________________________________________________ 27

8.5 JSP Life-Cycle ____________________________________________________________________ 27

8.6 Implicit Object ___________________________________________________________________ 28

8.7 Sciptlet Syntax. ___________________________________________________________________ 29

9 Reusable Web Component. ___________________________________________________ 30

9.1 include Directive __________________________________________________________________ 30

9.2 include Action ____________________________________________________________________ 30

10 JavaBeans ______________________________________________________________ 31

10.1 <jsp:useBean> ____________________________________________________________________ 31

10.2 <jsp:setProperty>, <jsp:getProperty> _________________________________________________ 32

10.3 JSP & Servlet Scope _______________________________________________________________ 32

11 Custom Tag._____________________________________________________________ 33

11.1 Step 1 : Tag Handler (java file) _______________________________________________________ 33

11.2 Step 2 : Tag Library Descriptor (tld file) - <taglib>, <listener>, <tag>, <attribute> _______________ 35

11.3 Step 3 : DD (web.xml) - <taglib>______________________________________________________ 36

11.4 Step 4 : taglib Directive (jsp page) - <%@taglib …% > ____________________________________ 36

11.5 Step 5 : Using Custom Tag (jsp page) - <prefix:tagname> __________________________________ 36

12 J2EE Design Pattern.______________________________________________________ 37

제 3 장. Design Pattern 상세. ___________________________________________________ 39

1 Value Objects _____________________________________________________________ 39

2 Model-View-Control(MVC). __________________________________________________ 40

3 Data Access Object (DAO). ___________________________________________________ 43

4 Business Delegate. __________________________________________________________ 44

제 4 장. 참고 자료. ___________________________________________________________ 46

1 Servlet API _______________________________________________________________ 46

1.1 Servlet Interface __________________________________________________________________ 46

1.2 ServletConfig Interface _____________________________________________________________ 46

1.3 ServletContext Interface ____________________________________________________________ 46

1.4 ServletRequest Interface ____________________________________________________________ 47

1.5 ServletResponse Interface___________________________________________________________ 49

1.6 abstract class GenericServlet implements Servlet, ServletConfig, Serializable__________________ 50

1.7 abstract class HttpServlet extends GenericServlet________________________________________ 50

1.8 HttpServletRequest Interface ________________________________________________________ 50

Page 4: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

1.9 HttpServletResponse Interface _______________________________________________________ 52

1.10 HttpSession Interface ______________________________________________________________ 54

1.11 RequestDispatcher Interface_________________________________________________________ 55

1.12 SingleThreadModel Interface ________________________________________________________ 55

1.13 ServletContextListener Interface _____________________________________________________ 55

1.14 ServletContextAttributeListener Interface _____________________________________________ 55

1.15 HttpSessionListener Interface _______________________________________________________ 55

1.16 HttpSessionActivationListener Interface _______________________________________________ 56

1.17 HttpSessionAttributeListener Interface ________________________________________________ 56

1.18 HttpSessionBindingListener Interface _________________________________________________ 56

2 web-app_2_3.dtd 분석.______________________________________________________ 57

3 Web-app_2_3.dtd 요약 & 예 (web.xml)________________________________________ 66

4 web-jsptaglibrary_1_2_dtd 요약. (tld file) _______________________________________ 69

Page 5: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

제 1 장. Servlets.

1 Servlet Model.

1.1 Http Method : HttpServlet abstract class.

1.1.1 적어도 다음 중 하나의 메소드를 오버라이딩해야 함.

? protected void doGet(HttpServletRequest req, HttpServletResponse res) throws

ServletException, IOException

? doPost, doPut

1.1.2 service 메소드는 오버라이딩할 필요 없음.

? service 메소드는 각 타입의 Http requests들을 핸들러 메소드들로 디스패칭하기 때

문.

1.2 Http Method 특징.

1.2.1 <FORM METHOD=”GET | POST | HEAD” ACTION=”sevlet_name”> : default는 GET.

1.2.2 HTTP POST

? socket을 통하여 request body의 일부로 전달.

? 길이에 제한없고, 정보가 숨겨져서 안전함. 일반적으로 HTML form 으로 보내짐.

? Bookmark 불가능하고, reload도 불가능할 수 있음.

1.2.3 HTTP GET : URI에 포함됨. 직접 입력, bookmark가능함.

1.2.4 HTTP HEAD : response에서 body가 필요 없는 GET request.

? Content-Type, Content-Length같은 정보만 필요할 경우.

? link validity, accessibility, recent modification 확인할 경우.

? service() method는 modified된 response object로 doGet()을 call하여, body의

output을 막음.

1.2.5 HTTP에서 header는 body보다 먼저 보내야 하므로, servlet container는 response

commit 전에 header를 써야 함.

1.3 Parameter, Header.

1.3.1 Servlet Initialization Parameter : cf) Servlet Context Initialization Parameter

? Enumeration ServletConfig.getInitParameterNames()

? String ServletConfig.getInitParameter(String name)

1.3.2 Request Parameter : ServletRequest interface, HttpServletRequest.

? Enumeration ServletRequest.getParameterNames()

? String ServletRequest.getParameter(String name)

1. getParameterValues의 첫번째 String.

? String[] ServletRequest.getParamete rValues(String name)

1. parameter name에 관련된 모든 parameter values의 String 배열.

2. 배열의 순서는 GET이 POST보다 먼저 옴.

1.3.3 Request Header : HttpServletRequest interface.

? Enumeration HttpServletRequest.getHeaderNames()

Page 6: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? String HttpServletRequest.getHeader(String name)

? Enumeration HttpServletRequest.getHeaders (String name)

1. 같은 이름의 여러 headers 가 있을 수 있음 (eg. Cache -Control headers).

? 다른 data type의 String표현을 포함하는 Header

1. int getIntHeader(String name) : NumberFormatException.

2. long getDateHeader(String name) : IllegalArgumentException

1.4 Response

1.4.1 Response Header : HttpServletResponse interface.

? void HttpServletResponse.setHeader(String name, String value) : 같은 이름 교체.

? addHeader : 주어진 이름의 header의 set에 추가됨.

? setIntHeader, setDateHeader, addIntHeader, addDateHeader.

? response가 commit된 다음에 set되는 header는 servlet container에 의해 무시됨.

1.4.2 Response Content Type : ServletResponse interface.

? void setContentType(String type)

1. character encoding type 포함 가능. (eg. text/html; charset=ISO-8859-4).

2. getWriter()를 call한다면, setContentType이 먼저 call되어야 함.

1.4.3 Response Body : ServletResponse interface.

? PrintWriter ServletResponse.getWriter() throws IOException

? ServletOutputStream ServletResponse.getOutputStream() throws IOException

1. MIME body response에서 binary data를 보내기 위해 사용.

2. Servlet container는 binary data 를 encoding하지 않음.

? flush() commits response.

1.5 Redirect

? void HttpServletResponse.sendRedirect(String url) throws IllegalStateException,

IOException

1. redirect page를 만들기 전에, status 를 SC_MOVED_TEMPORARILY로 set하고,

location header를 set, response buffer에 대한 implicit reset을 수행.

2. 상대경로 가능. => container가 fully qualified URL로 변환

3. 경로변환이 invalid하면, IllegalArgumentException.

4. redirect 기능이 없는 client들을 지원하기 위해 새로운 url의 hyperlink를 갖는

response body를 자동 생성하므로, 직접 body를 작성하지 말 것.

? sendRedirect & response commit

1. response를 commit하고, commit 되어 있다면 종료시키는 side effect.

2. 메소드 호출 후에 response에 쓰여진 data 는 무시됨.

3. response buffer에 commit되지 않은 data가 있으면, response buffer는 삭제 교체.

4. response가 commit되어 있다면, IllegalStateException.

1.6 Three Web Scopes : Request, Session, Context

1.6.1 Request : ServletRequest, HttpServletRequest interface

? Enumeration ServletRequest.getAttributeNames()

Page 7: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? void setAttribute (String name, Object value) : RequestDispather와 같이 자주 사용.

? getAttribute , removeAttribute

? ServletInputStream getInputStream() throws IOException

1. ServletInputStream을 사용하여 binary data로 request의 body를 얻음.

? String ServletRequest.getCharacterEncoding () : request body encoding.

? int ServletRequest.getContentLength() : request body length

? String ServletRequest.getContentType() : request body mime type

? String ServletRequest.getProtocol() : protocol/version (예. HTTP/1.1)

? Locale ServletRequest.getLocale (), Enumeration ServletRequest.getLocales ()s

? String ServletRequest.getScheme () : request scheme (예. ftp, http, https)

? String ServletRequest.getServerName ()

? int ServletRequest.getServerPort()

? String HttpServletRequest.getAuthType() : (예. BASIC, SSL)

? String HttpServletRequest.getMethod() : (예. GET, POST, HEAD, PUT)

? String HttpServletRequest.getContextPath()

? String HttpServletRequest.getPathInfo ()

1. extra path info (string following servlet path but preceding query string)

? String HttpServletRequest.getPathTranslated()

1. translates extra path info to a real path on the server

? String HttpServletRequest.getServletPath()

1. servlet path and name, but no extra path info

? String HttpServletRequest.getRequestURI()

? String HttpServletRequest.getQueryString ()

? String HttpServletRequest.getRemoteUser() : authenticated 되지 않았다면, null

? Principal HttpServletRequest.getUserPrincipal() : authenticated 되지 않았다면, null

1.6.2 Session : HttpSession interface.

? Enumeration HttpSession.getAttributeNames()

? void HttpSession.setAttribute(String name, Object value) : 같은 name은 교체됨.

? getAttribute , removeAttribute

? invalid한 session에의 접근은 IllegalStateException

1.6.3 Context : ServletContext inteface.

? context의 object attribute는 같은 application의 어떤 servlet에서도 사용 가능함.

1. getAttributeNames , getAttribute , setAttribute , removeAttribute

2. ServletContext getContext(String url)

3. int getMajorVersion(), int getMinorVersion()

1) 이 container가 지원하는 Java Servlet API 의 major/minor version.

4. String getMimeType(String file) : file 이 null 이면 null 을 return.

5. String getRealPath(String path)

6. String getServerInfo () : container의 name 과 version

Page 8: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? HTML, GIF, JPEG 파일등, application의 일부인 static content document들의 계층에

직접 접근을 제공함.

1. Method

1) URL getResource(String path)

2) InputStream getResourceAsStream(String path)

2. documents들의 이 계층은 remote server, other location에 있을 수도 있음.

3. 이 메소드들은 dynamic content를 얻는 데 사용되지는 않음.

1) 예) getResource(“/index.jsp”) : 처리된 출력이 아니라, JSP source code 반환

1.7 Life-Cycle : Servlet interface.

1.7.1 Life-Cycle.

? servlet constructing.

? void init() throws ServletException

1. initializing : one time setup code

2. 첫번째 request에 의해 call되고, 각 user request에 대해 다시 call되지 않음.

3. init method 가 ServletException을 throw 하거나, 정해진 시간안에 return 하지

않으면, servlet 은 service 되지 않음.

? void service() throws ServletException, IOException

1. servlet이 request에 응답하도록 container에 의해 call됨.

2. calls from clients are handled : doGet, doPost 등이 call하게 됨.

3. servlet은 전형적으로 각각의 request에 대해 별도의 thread를 갖는

multithreaded servlet container에서 실행.

? void destroy() : throws 없음

1. sevlet이 unloading되기 전에 실행되어 servlet 소멸.

2. closing db conneciton이 들어감.

3. super.destroy()는 GenericServlet.destroy()가 servlet이 destroy되는 log를 쓰도

록 함.

? garbage collecting.

? finalizing.

1.7.2 ServletConfig Servlet.getServletConfig () : startup information.

1.7.3 String Servlet.getServletInfo()

? servlet basic information (eg. author, version, copyright).

1.7.4 servlet reloading

? 대부분의 server들은 c lass file 이 변하면, 자동으로 servlet을 reload 함. Servlet 에

대한 request가 오면, 먼저 class file 이 바꼈는지 검사하여, 새로 class loader 를

만들고 전체 application context 를 reload 함.

? Core, primodial class loader 에 의해 load 되는 classpath 의 class 들의 변화는 영향

없음.

1.8 RequestDispatcher : Include / Forward.

1.8.1 javax.servlet. RequestDispatcher

Page 9: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? Sevlets와 JSP page들은 server administration 또는 DD(Deployment Descriptor)에

의해 naming될 수 있음.

? ServletConfig.getServletName () : Sevlet instance가 자신의 이름을 알 수 있음.

? RequestDispatcher Object는 request를 forwarding하거나, response에 resource를

including시키는 데 사용할 수 있음.

? 다른 context들에서 resource들에 대한 RequestDispatcher를 얻기 위해서는

getContext(String url)로 ServletContext를 얻어 사용함.

1.8.2 Method.

? RequestDispatcher ServletRequest.getRequestDispatcher(String url)

1. 경로는 현재의 servlet context 밖으로 확장할 수 없지만, 상대경로를 쓸 수 있음.

? RequestDispatcher ServletRequest.getNamedDispatcher(String name)

1. name은 web.xml에 등록된 servlet name.

? ServletContext.getRequestDispatcher(String url)도 있지만, 절대 경로만을 받고,

deprecated될지도 모름.

1.8.3 Include

? void RequestDispatcher.include (ServletRequest request, ServletResponse

response) throws ServletException, IOException

? Server-side including을 할 수 있음.

? ServletResponse object는 호출하는 쪽으로부터 바뀌지 않은 경로 element들과

parameter들을 가짐.

? Included된 servlet은 response status code를 바꾸거나 header들을 set할 수 없음.

=> 무시됨.

? Include된 resource는 같은 output mechanism을 사용해야 함. (text or binary)

? request와 response는 service()에 전달된 것과 같은 객체여야 함.

? target 으로의 정보전달에 query string 또는 setAttribute()를 사용할 수 있음.

? Include 는 언제든지, 심지어 flush 가 call 된 후에도 call 할 수 있음.

1.8.4 Forward

? void RequestDispatcher.forward (ServletRequest request, ServletResponse

response) throws ServletException, IOException

? Response를 생성하기 전에 선처리를 할 수 있게 함.

? Output을 생성할 수 없지만, header들은 set할 수 있음.

? getRequestDispatcher()로 얻어진 RequestDispatcher에 대해 ServletRequest Object

는 target resource의 경로에 맞춰진 path elements 들과 parameter들을 가짐.

? Response가 commit되기 전에 forwarding되어야 함.

1. IllegalStateException

2. commit 안된 response는 forwarding되기 전에 buffer에서 자동 삭제됨.

? request와 response는 service()에 전달된 것과 같은 객체여야 함.

? target으로의 정보전달에 query string 또는 setAttribute()를 사용할 수 있음.

? 상대 경로를 포함하는 page로 forwarding하는 것은 link가 깨질 수 있으므로 삼가는게

Page 10: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

좋음. 대신 sendRedirect()를 사용함.

? forwarding일 때는 browser의 URL 표시가 forwading전의 주소가 표시되고, redirect

일 때는 redirect후의 주소가 표시됨.

1.8.5 예.

RequestDispatcher rd;

ServletContext sc = getServletContext();

rd = sc.getRequestDispatcher(“/login_fail.jsp”);

rd.forward(req, res);

Page 11: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

2 Servlet Container Model.

2.1 Servlet Context Init Parameter : <context-param>

2.1.1 Servlet Context Init Parameter

? String ServletContext.getInitParameter(String name)

? Enumeration ServletContext.getInitParameterNames()

? Initialization parameter들은 setup information을 전달하기 위해 사용.

1. 예) webmaster’s e-mail address, 중요한 data를 가진 system name.

2.1.2 <context-param>

? <!ELEMENT context-param (param-name, param-value, description?)>

? <!ELEMENT param-name (#PCDATA)> : application.에서 unique.

? <!ELEMENT param-value (#PCDATA)>

2.2 Listener : <listener>

ServletContextListener, ServletContextAttributeListener

HttpSessionListener, HttpSessionActivationListener

HttpSessionAttributeListener, HttpSessionBindingListener

2.2.1 ServletContextListener

? Servlet context의 변화에 대해 notification을 받기 위해 implement한 class는 반드시

application에 대해 deployment descriptor에서 configure되어야 함.

? Application에 대해 VM level에서의 resource들과 state를 관리하기 위해 사용.

? void contextInitialized(ServletContextEvent sce)

1. application이 request들을 처리할 준비됨을 공지함.

2. server startup, context added 또는 reloaded되었음.

? contextDestroyed : application이 shutdown, context가 remove 또는 reload될 것임.

2.2.2 ServletContextAttributeListener

? Servlet context의 attribute list 변화에 대해 notification을 받기 위해, implement된

class는 반드시 application에 대해 deployment descriptor에서 configure되어야 함.

? void attributeAdded(ServletContextAttributeEvent scae)

? attributeRemoved, attributeReplaced

2.2.3 HttpSessionEvent

? HttpSessionListener

1. session의 생성, 소멸에 대해 notification을 받기 위해 implement한 class는 반드

시 application에 대해 deployment descriptor에서 configure되어야 함.

2. void sessionCreated(HttpSessionEvent se), sessionDestroyed

? HttpSessionActivationListener

1. Session migration에 사용함. Session에 바운딩된 Object들은 session이

passivated(move)될지 activated(alive)될지 알려주는 container event들을 listen

할 수 있음.

2. VM들 사이에서 session을 migrate하거나 session을 persist하는 container는

Page 12: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

HttpSessionActivationListener를 implement하는 session들에 bound된 모든

attribute들에 notify해야 함.

3. void sessionWillPassivate (HttpSessionEvent e)

1) session이 move될 예정임.

2) call되었을 때, session은 이미 out of service.

4. sessionDidActivate

1) session이 새로운 server에서 activated되었음.

2) call되었을 때, session은 아직 in service가 아님.

2.2.4 HttpSessionBindingEvent

? HttpSessionAttributeListener

1. Session의 attribute list 변화에 대해 notification을 받게 됨.

2. void attributeAdded(HttpSessionBindingEvent hsbe)

3. attributeRemoved, attributeReplaced

? HttpSessionBindingListener

1. Object가 session으로부터 바인딩 또는 언바인딩될 때 notification을 받음.

2. session invalidating 또는 session time -out 때문에, session으로부터 attribute 를

명시적으로 언바인딩시킨 결과일 수 있음.

3. void valueBound (HttpSessionBindingEvent e)

4. valueUnbound : removed, replaced, or invalidated.

5. Container는 valueBound 를 call하고, application에 있는 모든

HttpSessionAttributeListener들에 notify함.

2.2.5 <listener>

? <!ELEMENT listener (listener-class)> : 하나씩 밖에 설정 못함. “+|*”가 없음.

? <!ELEMENT listener-class (#PCDATA)>

1. application의 listener bean에 등록되어야 함. fully qualified class name.

2.3 Distributable Application.

2.3.1 목적 : clustering, scalability, failover를 위해 multiple JVM들에 분산.

2.3.2 Context

? 생성된 local VM에 존재. Container의 VM scope.

? 분산환경에서, Servlet Context의 instance가 각 JVM에 존재할 수 있으므로,

application state는 Session, DB, EJB에 없으면, 분산된 공유 메모리 저장으로 불가.

? Listener들은 다른 JVM에는 영향을 주지 않음.

2.3.3 Container

? 각 container는 자신의 분리된 event들의 복사를 가짐.

? context나 session event들을 다른 VM들로 전달할 필요 없음.

Page 13: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

3 Structure & Deployment.

3.1 Application Structure

3.1.1 Context Path

? application content들의 URL namespace를 결정.

? 같은 이름의 context path는 container에 의해 거부되어야 함.

? case-sensitive.

3.1.2 WEB-INF

? Application의 document root에 없는 application에 관련된 모든 것을 포함.

1. web.xml, tld files, other xml config files.

? Application의 공식적인 document tree의 일부가 아님 : invisible outside container.

? WEB-INF에 아무 파일도 없으면, container는 client에 직접 serving함.

? ServletContext의 getResource(), getResourceAsStream()에 의해 WEB-INF의

content들을 볼 수 있음.

? servlet code를 통해 access 가능하고, client에게 노출되길 바라지 않는 Application

specific configuration 정보들을 둘 수 있음.

1. Deployment descriptor : /WEB-INF/web.xml

2. compiled classes : /WEB-INF/classes/*

3. Jarred classes : /WEB-INF/lib/*.jar

1) Application class loader는 먼저 /WEB-INF/classes 디렉토리에서 찾고, 다음

에 library JAR 파일들에서 찾음.

2) Library JAR 파일들은 WAR archive entry들에 나타난 순서에 따라 load됨.

3.1.3 WAR file

? Application structure의 JAR file.

? Server의 webapps directory에 위치할 수 있어서, startup시에 server가 extract.

3.2 <servlet>, <servlet-mapping>

3.2.1 <servlet>

? <!ELEMENT servlet (icon?, servlet-name , display-name?, description?, (servlet-

class|jsp-file), init-param*, load-on-startup?, run-as?, security-role-ref* )>

1. JSP 파일이 specified되고, load-on-startup element가 존재하면, JSP 파일은

precompile되고 load되어야 함.

? <!ELEMENT servlet-name (#PCDATA)>

1. dd 내에서 쓰이는 logical name. canonical name. application에서 unique.

? <!ELEMENT sevlet-class (#PCDATA)> : Fully qualified class name.

? <!ELEMENT init-param (param-name, param-value, description?)>

3.2.2 <servlet-mapping>

? <!ELEMENT sevlet-mapping (servlet-name , url-pattern)>

1. logical servlet name과 url pattern 사이의 mapping을 정의.

2. mapping순서

Page 14: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

1) explicit mapping : /index.html

2) prefix mapping : /kyo/*

3) extension mapping : *.jsp

4) default mapping : “/”. application에 대한 default sertvlet을 indentify.

? <!ELEMENT url-pattern (#PCDATA)>

3.2.3 예.

<servlet>

<servlet-name>catalog</servlet-name>

<servlet-class>com.mycorp.CatalogServlet</servlet-class>

<init-param>

<param-name>catalog</param-name>

<param-value>Spring</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>catalog</servlet-name>

<url-pattern>/catalog/*</url-pattern>

</servlet-mapping>

Page 15: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

4 Session Management.

4.1 Session

4.1.1 Session

? User identification이나, user에 대한 정보를 하나 이상의 connection 또는 request에

걸쳐 저장하는 방법.

? 일반적으로 사이트를 여러 번 방문할 수 있는 one user에 적용됨.

? Session은 scope가 application level이므로, Servlet은 다른 context의 session들에는

access할 수 없음.

4.1.2 HttpSession

? HttpSession HttpServletRequest.getSession([boolean create])

1. argument가 없거나 true이면, session이 없을 경우 생성.

? Session이 적절하게 유지되고 있음을 확인하기 위해, response를 commit하기 전에

getSession을 call.

? String HttpSession.getId () : container에 할당된 unique session identifier

4.2 Session Invalidating : <session-config>

4.2.1 Session Timeout

? long HttpSession.getLastAccessedTime ()

1. session 에 관련된 마지막 request를 보낸 시간.

? HTTP protocol에서는 client의 종료를 명시적으로 알 수 없음. : timeout 사용.

? int HttpSession.getMaxInactiveInterval()

1. servlet container에 의해 정의된 session들에 대한 Default timeout period를 얻음.

? void HttpSession.setMaxInactiveInterval(int seconds ) : 음수이면, never expire.

? req.isRequestedSessionIDValid ()

4.2.2 void HttpSession.invalidate() : “logout”.

? session을 invalidate시키고, 바인딩된 모든 객체들을 언바인딩시킴.

? Shutdown은 server에 따라 session을 invalidate시킬 수도 있고 아닐 수도 있음.

4.2.3 <session-config>

? <!ELEMENT session-config (session-timeout?)>

? <!ELEMENT session-timeout (#PCDATA)>

1. minutes로 정의. (Tomcat default : 30).

2. Timeout이 0보다 작거나 같으면, session은 expire되지 않음.

<session-config><session-timeout>30</session-timeout></session-config>

4.3 Session Tracking.

4.3.1 HTTP Cookie : isRequestedSessionIdFromCookie

? Session tracking에 가장 많이 사용되고, 모든 container는 이를 지원해야 함.

? Container가 client로 cookie를 보내면, client는 계속되는 request마다 cookie를

return. (명확히 request를 session에 관련시킴).

? Session tracking cookie의 name은 JSESSIONID여야 함.

Page 16: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

Cookie cookie = new Cookie(“name”, “value”); res.addCookie(cookie);

Cookie[] cookies = req.getCookies();

4.3.2 URL-Rewriting : isRequestedSessionIdFromURL

? 보통 최후의 선택으로 사용하는 방법.

? Client가 cookie를 거부하면, URL-rewriting이 server에 의해 session tracking의 기

반으로 사용될 수 있음.

? Session id는 URL string 에서 path parameter로서 encoding 됨.

? Parameter의 name 은 jsessionid여야 함.

? 추가된 data와 session id를 포함하는 URL-rewriting은 container에 의해 해석되어

request를 session에 관련시킴.

? 예) http:/www.myserver.com/index.html;jsessionid=1234

? String HttpServletResponse.encodeURL(String url), encodeRedirectURL

1. url을 session id를 포함하도록 encoding한 새로운 url return.

2. encoding이 필요하지 않거나, 지원되지 않으면, url은 변하지 않음.

? url rewrting에 의한 session tracking은 multipe browser window일 때, window가 어

떻게 생성되었는지, window를 만든 link가 url rewriting인지의 상황에 따라 다른 혹

은 같은 session일 수 있음.

Page 17: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

5 Server-Side Exception.

5.1 Error Page.

5.1.1 Exception Handling

? Servlet이 request 처리동안에 throwing 하는 Exception.

1. runtime exceptions or errors

2. ServletExceptions or subclasses thereof

1) UnavailableException

3. IOExceptions or subclasses thereof

? Response에 error를 나타내는 status code가 set되면, container는 application에 대해

DD에서 정의된 error page declaration들의 list에서 맞는 status -code syntax에 해

당하는 resource들을 service back함.

? Servlet이 error page로 처리되지 않는 error를 발생시키면, container는 response

status code를 SC_INTERNAL_SERVER_ERROR(500)로 set해야 함.

? RequestDispatcher를 사용해서 불려진 servlet들에서 발생한 error들에 대해서는

error page가 적용되지 않음. => RequestDispatcher를 사용한 servlet쪽에서 처리함.

5.1.2 Exceptio n

? exception-type syntax를 error page 선언에 사용하면, 해당하는 exception에 대한

resource들을 service back.

1. 계층상 가까운 쪽이 선택됨.

2. 가능한 exception-type이 없어서 ServletException(or subclass thereof)이

thrown되면, container는 ServletException.getRootCause()에 의해 정의된대로

wrapped exception을 extract함.

3. 그것은 error page 선언들을 wrapped exception을 사용하여 다시 한번 검사함.

? ServletException은 msg를 주든지 아니면, “root cause”를 선택할 수 있음.

1. 예) throw new ServletException(“execution interrupted”, InterruptedException);

2. Throwable ServletException.getRootCause() : root cause exception 반환.

? exception object 그 자체는 이용불가하므로, stack trace를 얻을 방법은 없음.

5.2 <error-page>

5.2.1 <!ELEMENT error-page ((error-code | exception-type), location)>

? <!ELEMENT error-code (#PCDATA)> : unique

? <!ELEMENT exception-type (#PCDATA)> : fully qualified class name. unique.

? <!ELEMENT location (#PCDATA)>

1. location은 ‘/’로 시작해야 함.

2. dynamic page 가능 : javax.servlet.error.status_code, exception_type, message

5.2.2 예

<error-page>

<error-code>404</error-code>

<location>/404.html</location>

Page 18: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

</error-page>

<error-page>

<exception-type>java.lang.NumberFormatException</exception-type>

<location>/MyException.html</location>

</error-page>

5.3 sendError, setStatus

5.3.1 void HttpServletResponse.sendError(int statusCode [, String msg]) throws

IllegalStateException, IOException

? Status code를 사용하여 buffer를 clear하고 error response를 보냄.

? content body에 쓰일 메시지 parameter로 service back할 수 있음.

1. default HTML-formatted server error page는 cookies들과 다른 header들은 변

경없이 content type을 “text/html”로 한 specified 메시지를 가짐.

? sendError & response commit

1. response를 commit하고, commit 되어 있다면 종료시키는 side effect.

2. 메소드 호출 후에 response에 쓰여진 data 는 무시됨.

3. response buffer에 commit되지 않은 data가 있으면, response buffer는 삭제 교체.

4. response가 commit되어 있다면, IllegalStateException.

5.3.2 void HttpServletResponse.setStatus(int statusCode)

? Response에 대한 status code를 set함.

? Error가 없을 때, 예로 SC_OK(200) or SC_MOVED_TEMPORARILY를 반환하기 위해

사용함. (Error가 있으면, 대신 sendError 메소드가 사용됨).

? SC_NOT_FOUND(404), SC_UNAUTHORIZED(401), SC_NO_CONTENT,

SC_MOVED_PERMANENTLY, SC_INTERNAL_SERVER_ERROR(500),

SC_NOT_IMPLEMENTED, SC_SERVICE_UNAVAILABLE(503).

? response commit후의 호출은 무시됨.

5.4 log.

(servlet log file의 name과 type은 servlet container에 따라 정해져 있음)

5.4.1 HttpServlet(inherited from GenericServlet)

? void log(String msg) : servlet name이 앞에 첨가된 specified message를 씀. 일반적

으로 event log.

? void log(String msg, Throwable t)

1. exception에 대해 servelet name이 앞에 첨가된 message와 stack trace를 씀.

5.4.2 ServletContext

? void log(String msg) : specified message를 씀. 일반적으로 event log.

? void log(String msg, Throwable t) : exception에 대해 message와 stack trace를 씀.

Page 19: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

6 Security.

6.1 보안 용어.

? Authentication : verifiy identity.

? Authorization : Authenticated된 user가 resource에 access하는게 허용됨.

? Access control for resources

1. 부여된 무결성, 신뢰성, 이용 제약 조건등의 목적에 맞는 경우에, 접근을 허용.

? Auditing : application내에서 user의 행동들을 permanent log에 기록.

? Malicious code : Security rule들을 파괴하기 위한 code

? Web site attaks : application에 대한 hacker들의 외부 공격

? Data Integrity : 정보가 전달되는 동안 제 3자에 의해 변경되지 않음.

? Confidentiality or Data Privacy : 정보가 접근할 권한을 부여받은 user들에게만 이용.

6.2 <security-role-ref>, <security-constraint>, <security-role>

6.2.1 <security-role-ref>

? <!ELEMENT security-role-ref (description?, role-name, role-link?)>

1. role-name “*”은 특별한 의미를 가지므로, 쓸 수 없음.

? <!ELEMENT role-link (#PCDATA)>

1. security role reference를 정의된 secrity role에 link시킴.

2. security-role element들에서 정의된 security role들중 하나의 <role-name>과 같

아야 함.

6.2.2 <security-constra int>

? <!ELEMENT security-constraint (display-name?, web-resource-collection+, auth-

constraint?, user-data-constraint?)>

6.2.3 <web-resource-collection>

? <!ELEMENT web-resource-collection (web-resource-name, description?, url-

pattern*, http-method*)>

? <!ELEMENT http-method (#PCDATA)>

1. HTTP method (GET | POST | …)를 가짐.

2. 아무 HTTP method도 specified되지 않으면, security constraint는 모든 HTTP

method들에 적용됨.

6.2.4 <auth-constraint>

? <!ELEMENT auth-constraint (description?, role-name*)>

1. resource들에 접근하기 위해 user들이 속해야 하는 security roles.

2. 아무 role도 정의되지 않으면, 어느 user도 이 부분에 접근이 허용되지 않음.

? <!ELEMENT role-name (#PCDATA)>

1. role-name은 <security-role>의 role-name과 일치하거나, 모든 role들을 나타내

는 reserved된 “*”이어야 함.

2. “*”과 role name들이 모두 나타나면, container는 모든 role들로 해석함.

3. role name들은 case-sensitive임.

Page 20: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

6.2.5 <user-data-constraint>

? <!ELEMENT user-data-constraint (description?, transport-guarantee)>

? <!ELEMENT transport-guarantee (#PCDATA)>

1. Client-Server의 transport layer에 대한 요구들을 표현함.

2. client와 server사이의 통신이 NONE, INTEGRAL, CONFIDENTIAL이어야 함.

3. NONE : application에 transport guarantee가 필요 없음.

4. 대부분의 경우에 INTEGRAL 또는 CONFIDENTIAL flag가 있으면, SSL의 사용이

필요하다는 것을 가리킴.

5. 원래의 request가 HTTP였다면, container는 HTTPS port로 redirect해야 함.

? multiple security constraint : “first match wins”.

6.2.6 <security-role>

? <!ELEMENT security-role (description?, role-name )>

? Application 개발자 또는 Assembler에 의해 정의된 user들의 logical g rouping.

? Application이 deployed될 때, Deployer는 security policy domain에서 security role

을 principal 또는 group에 mapping.

? Calling principal이 속한 user group은 security attribute들로부터 얻어짐. 그 group이,

security role이 mapping되어 있는 user group과 match되어야만 security role임.

? Principal object는 login하면, HttpSession object안에 생김.

? Container는 principal에 대한 선언적 또는 programmatic 한 security를 부여함.

6.2.7 예.

? security role reference “FOO”를 role -name “manager”인 security role에 mapping.

? security role “manager”에 속하는 user에 의해 called된 servlet은 API call인

is UserInRole (“FOO”)을 하고, 결과는 true가 됨.

<web-app>

<display-name>A Secure Application</display-name>

<servlet>

<security-role-ref>

<role-name>FOO</role-name>

<role-link>manager</role-link>

</security-role-ref>

</servlet>

<security-constraint>

<web-resource-collection>

<web-resource-name>SalesInfo</web-resource-name>

<url-pattern>/salesinfo/*</url-pattern>

<http-method>GET</http-method>

<http-method>POST<http-method>

Page 21: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

</web-resource-collection>

<auth-constraint>

<role-name>manager</role -name>

</auth-constraint>

<user-data-constraint>

<transport-guarantee>CONFIDENTIAL</transport-guarantee>

</user-data-constraint>

</security-constraint>

<security-role>

<role-name>manager</role-name>

</security-role>

</web-app>

6.3 Authentication Type : BASIC, DIGEST, CLIENT-CERT, FORM

6.3.1 HTTP Basic Authentication : HTTP/1.0 specification.

? Username/Password

1. server가 client에 user를 authenticate하도록 authenticated될 realm (string)을

포함하는 request를 보냄.

2. Browser는 pop-up dialog로 이것을 받아 잇따른 request들을 위해

authentication info를 cache함.

3. realm은 이것을 참조하는 다른 security policy domain에 영향을 주어서는 안됨.

? 단점

1. HTTPS(with SSL)이 아니면, pwd는 단순한 base64 encoding으로 안전하지 않음.

2. pwd들은 종종 server에서 text로 저장.

? 장점

1. 구현하기 쉬움.

2. 낮은 보안 환경에 유용 (예. Subscription-based online newspaper).

6.3.2 HTTP Digest Authentication

? Username/암호화된 Password (digest)

1. base64 encoding보다 안전하게 암호화된 password를 전달.

2. password 의 digest는 username, password, uri, http method, 그리고 server가

만든 임의의 nonce value 의 hash로 만들어짐. Server는 digest를 계산하고,

user 가 보낸 digest와 비교함.

? 단점

1. server는 원래의 password들의 database를 유지해야 함.

2. 많은 browser들에서 지원이 안됨. (IE 5.x 이상에서 지원됨).

? 장점

1. 각 digest는 single uri request와 nonce value에 대해서만 valid하므로, basic

authentication보다 secure.

Page 22: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? 현재 많이 사용되지 않으므로, container들은 권장되지만 지원할 필요는 없음.

6.3.3 Form Based Authentication

? User가 보호된 resource에 접근하려고 하면, container는 user authentication을 검사.

1. authenticated되어 있고 접근 authority를 가지고 있으면, resource는 activate되고

resource에 대한 reference가 반환됨.

2. authenticated되어 있지 않으면, 다음의 절차를 따름.

1) 그 security constraint에 관련된 login form이 client에 보내지고,

authentication을 triggering하는 URL path가 container에 저장됨.

2) Container는 post back된 form의 정보로 user를 authenticate하려고 함.

3) Authentication이 실패하면, forward 또는 redirect를 사용하여 <form -error-

page>가 반환되고, response의 status code는 401.

4) Authentication이 성공하면, authenticated된 user’s principal이 resource 접근

에 대한 authorized role인지 체크됨.

5) User가 authorized되어 있으면, 저장된 URL path를 사용하여 client를 redirect.

6) authenticated되지 않은 user에게 보내지는 Error page는 실패에 대한 정보를

포함함.

? 단점

1. Basic과 같은 결점인 security 문제. (SSL이 아니면, password가 plain text).

2. Basic과 같은 결점인 standard logout 기능이 없음.

3. Basic과 같은 결점인 server가 authenticate하도록 의존하므로, username과

password 이외의 custom field들(예. 주민등록번호)을 이용하지 못함.

4. error page가 access 거부의 정보에 대한 access, 심지어 user가 재시도하기 위해

지적해야 하는 page에 대한 access를 갖지 않음.

? 장점 : Login screen의 “Look and Feel”을 조절할 수 있음.

? Syntax

1. login form의 action은 j_security_check여야 함. 이 제한은 login form이 어떤

resource를 위해 동작하든지, 그리고 server에 form 에서 outbound된 action field

를 sepcify하도록 요구하는 것을 피하기 위함.

2. username은 “j_username”, password는 “j_password”의 이름을 가져야 함.

<form method=”POST” action=”j_security_check”>

<input type=”text” name=”j_username”>

<input type=”password” name=”j_password”>

</form>

6.3.4 CLIENT-CERT Authentication

? Public Key Certificate(PKC) 사용

? Authenticate server and optionally the client

? 많은 browser들은 certificate를 보내기 전에 user에게 pwd를 요구.

? Browser가 certificate를 갖지 않거나, authorized되지 않았다면, 거부됨.

Page 23: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? 단점

1. user가 signed된 certificate를 install하고 있어야 함.

2. server는 받은 모든 public key들의 database를 유지해야 함.

3. server는 우선 SSL 3.0을 지원해야 함.

? 장점

1. login page가 필요 없음.

2. 강력한 authentication : 암호화된 connection을 제공.

3. e-commerce application들, browser내 single -SignOn에 유용함.

6.4 <login-config>

? <!ELEMENT login-config (auth-method, realm-name?, form-login-config?)>

? <!ELEMENT realm-name (#PCDATA)> : Basic authentication이 아니면, 무시됨.

? <!ELEMENT auth-method (#PCDATA)>

1. application에 사용될 authentication mechanism을 정의.

2. 보호되는 resource들에 접근하려면, authentication mechanism을 사용하여

authenticated되어야 함.

3. “BASIC”, “DIGEST”, “FORM”, “CLIENT-CERT”의 값을 가져야 함.

? <!ELEMENT form-login-config (form-login-page, form-error-page)>

1. form based authentication이 아니면, 무시됨.

? <!ELEMENT form-login-page (#PCDATA)> : “/”로 시작.

? <!ELEMENT form-error-page (#PCDATA)> : “/”로 시작.

6.4.2 예.

<login-config>

<auth-method>BASIC/DIGEST/FORM/CLIENT-CERT</auth-method>

<realm-name> HTTP Realm Name </realm-name>

<form-login-config>

<form-login-page>/loginpage.html</form-login-page>

<form-error-page>/errorpage.html</form-error-page>

</form-login-config>

</login-config>

Page 24: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

7 Thread-safe Servlets.

7.1 thread-safe?

? local variables : yes

? instance variables : no

1. single instance handle multiple service requests.

2. single thread model일 경우는 yes.

? class variables : no, class variable is accessed by multiple servlets .

? request attributes : yes, request object is a local variable

? session attributes : no

? context attributes : no

7.2 Number of Instances

? SingleThreadModel interface를 implements하지 않고, 분산 환경이 아닌(default)

servlet에 대해서, container는 servlet 선언마다 하나의 instance만 사용해야 함.

? SingleThreadModel interface를 implements하는 servlet에 대해서, container는

heavy request load를 처리하고 특별한 instance에 대한 request들을 serialize하기

위해, multiple instance들을 instantiate할 수 있음.

? Servlet이 deployment descriptor에서 “distributable”로 mark된 application의 일부로

deployed된 경우에, container는 VM마다 servlet 선언당 하나의 instance만 가질 수

있음.

? Servlet이 SingleThreadModel을 implements한 distributable application에 있으면,

container는 container의 각 VM에서 multiple instance들을 instantiate할 수 있음.

7.3 Multi-Thread Model

? 등록된 이름당 하나의 servlet instance

? 각 request에 대해, service()를 실행하는 별도의 thread가 생김.

? Instance variable들에 대한 access를 synchronize해야 함.

7.4 Single-Thread Model

? 등록된 이름당 servlet instance들의 pool.

? service()에 동시에 하나의 thread만 실행됨을 server가 보장.

? Thread-safe하고, instance variable들에 대해 synchronize할 필요 없음.

? Servlet scope 밖의 static variable들, object들과 같은 공유된 resource들을 access하

는 servlet들로부터의 synchronization 문제를 막지 못함. (예. ServletContext,

HttpSession)

? instance들의 생성에는 한계가 있을 수 있음. (예, database connection)

? SingleThreadModel을 implement하지 않은 servlet들에 대해서, service method(또는

HttpServlet abstract class의 service method로 dispatched된 doGet, doPost같은

method들)가 synchronized로 정의되어 있으면, container는 instance pool을 사용한

접근을 할 수 없고, request들을 serializing해야 함.

? 성능상 나쁜 영향 때문에 service method를 synchronizing시키지 말 것이 권장됨.

Page 25: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

7.5 javax.servlet.SingleThreadModel interface.

? Servlet이 single thread model을 사용하도록 선언하는데 사용되는 Interface

? empty “tag” interface : 아무 method도 갖고 있지 않음.

? Container는 하나의 servlet instance에 대한 접근을 synchronizing하거나, servlet

instance들의 pool을 유지하면서 새로운 request마다 free servlet에 dispatching함으

로써, 이 보장을 가능하게 함.

7.6 Thread Safety

? request와 response object들의 implementation은 thread-safe를 보장하지 않음.

Thread를 처리하는 request의 scope내에서만 사용되어야 함을 의미.

? request와 response object들에 대한 reference는, 비결정적일 수 있는 결과 때문에,

다른 thread들에서 실행되는 object들에게는 주어지지 말아야 함.

? Request thread들을 실행하는 multiple servlet들은 동시에 하나의 session object에

active access를 가질 수도 있음. 개발자는 session resource들에 대한

synchronizing access가 적절하도록 책임을 가짐.

7.7 Listener Instances and Threading

? Container는 application에의 첫번째 request의 실행에 앞서 application에 있는

listener class들의 instantiation을 완료해야 함. application에 대한 마지막 request가

service될 때까지 각 listener를 reference해야 함.

? ServletContext와 HttpSession object들에 대한 Attribute 변경이 동시적으로 일어날

수 있음.

? Container는 attribute listener class들에 대한 결과 notification들을 synchronize할

필요 없음. 상태를 유지하는 Listener class들이 data integrity에 대해 책임을 갖고,

명시적으로 이 경우를 처리해야 함.

Page 26: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

제 2 장. JSPs.

8 The JSP Model

8.1 JSP Tag Syntax

? Directive : <%@ directive {attr=”value” or ‘value’}* %>

? Declaration : <%! JavaDeclaration(s) %>

? Scriptlet : <% JavaStatements %>

? Expression : <%= JavaExpression %> : 뒤에 ‘;’이 없음.

8.2 JSP Tag 특성

8.2.1 Directive

? JSP page에 의해 받은 어떤 request에도 독립적인 global 정보.

? Translation and Compilation phase를 위한 정보.

? JSP container에 대한 message들.

8.2.2 Scripting elements

? Template text와 action들에 끼워넣어짐.

? Declaration

1. JSP page에서 사용된 scripting language에 있는 변수들과 메소드들을 선언.

2. Class level declarations , No output

3. implicit variable들은 사용 불가. => _jspService()에 선언되어 있음.

? Scriptlet

1. language directive에서 정의된 scripting language에 적합한 모든 code fragment

들을 가질 수 있음.

2. out이 사용되지 않으면, No ouput.

? Expression : 평가되어 결과가 String으로 out JspWriter에 출력됨.

8.3 page Directive

8.3.1 page에 의존적인 많은 property들을 정의하고, JSP container에 전달.

8.3.2 <%@page {...} %> : default는 다음과 같음.

? language=”java”, contentType=”text/html;charset=ISO-8859-1”

? import=”java.lang.*, javax.servlet.*,javax.servlet.jsp.*,javax.servlet.http.*”

1. import만, 여러 page directive들에 사용될 수 있음.

2. 하나 이상의 import assignment들을 가질 수 있음.

? session=”true” : “false”이면, implicit session을 쓸 수 없음.

? isErrorPage=”false” : “true”이면, implicit exception을 쓸 수 있음.

? errorPage=”…” : no default.

? autoFlush=”true” : “false”이면, buffer가 full일 때 exception.

? buffer=”8kb” : “none”은 buffer를 disable.

? Info=”…” : no default. description of the jsp page.

? isThreadSafe=”true” : “false”이면, SingleThreadModel.

Page 27: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? extends =”…”

1. no default. Fully qualified class name.

2. class는 JspPage 또는 HttpJspPage interface를 implement해야 함.

8.4 Equivalent XML-based Tag.

8.4.1 Directive : <%@page info=”Eample” %> == <jsp:directive.page info=”Example” />

8.4.2 Declaration : <jsp:declaration> … </jsp:declaration>

8.4.3 Scriptlet : <jsp:scriptlet> … </jsp:scriptlet>

8.4.4 Expression : <jsp:expression> … </jsp:expression>

8.4.5 예외.

? <%@ taglib uri=”…” prefix=”pre” %> == <jsp:root xmlns:pre=”…”></jsp:root>

8.5 JSP Life-Cycle

Page Translation => Compilation => Load Class => Create Instance =>

Call jspInit => Call _jspService => Call jspDestroy

8.5.1 JSP Life Cycle Information

? JSP page는 textual component임. Translation phase와 Request phase의 두 phase가

있음. Translation phase는 page마다 한번만 이루어짐. Request phase는 request마다

한번씩 이루어짐.

? JSP page는 servlet class를 생성하기 위해 translated되고, JSP page implementation

class는 request time에 instantiated됨. Instantiated된 JSP page object는 request들

을 처리하고, response들을 생성함.

8.5.2 Translation phase

? JSP page는 JSP page의 textual representation으로 처리할 수 있는 servlet class를

application에 제공하기 위해서, 사용하기 전에 translated될 수 있음.

? JSP source page의 implementation class로의 translation은 JSP page를 container에

initial deployment할 때와 client의 request를 받고 처리하는 사이(on-demand)의 어

떤 때에도 일어날 수 있음. 개발 동안에 deployment 정보를 덧붙여 implementation

class로 compile될 수도 있음.

? Translation phase 동안에 container는 JSP page에 상응하는 JSP page implementatin

class를 위치시키거나 생성함. 이 process는 JSP page의 semantics에 의해 결정됨.

Container는 표준 directive들, acction들과 page에서 사용된 tag library들을

reference하는 custom action들을 해석함. Tag library는 JSP page가 그 library를 옳

게 사용하는지 적합성을 검사하는 method를 제공할 수도 있음.

? Container는 JSP page implementation class의 세세한 점에서 유동성을 가짐으로써,

가장 부각되는 performance issue인 QOS(quality-of-service)를 address하기 위해

이를 이용할 수 있음.

8.5.3 Request phase

? container는 request들과 event들에 대한 response에 이 class의 하나 이상의

instance들을 다룸.

? Container는 request와 response object들을 instantiating해야 하고, 적절한 JSP page

Page 28: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

implementation object를 호출해야 함.

? Processing을 완료할 때, response object는 container를 통해 client로 보내짐.

? 첫번째 request가 JSP page에 전달되면, jspInit()가 있으면, page를 준비하기 위해 call

됨. 비슷하게 container는 request가 service되고 있지 않을 때, JSP page에 사용된

resource들을 요구하기 위해 언제든지 jspDestroy()를 호출할 수 있음.

8.5.4 Order of Events

? JSP page는 개발 기간이나, deployment time에 compile될 수 있음. Compilation 동안

에 JSP page는 implementation class (Servlet)으로 변환됨.

1. Page Translation : jsp를 servlet code로 translate.

2. Compilation : servlet code로부터 implementation class로 compile.

? Page가 request되면, container는 class를 load하고 그 class의 instance를 생성함.

(Load Class > Create Instance)

? 첫번째로 JSP page가 requested되면, jspInit() method가 call되고, request는

_jspService() method로 처리됨. (Call jspInit > Call _jspService)

? container가 page 처리를 종료하면, jspDestroy() method가 call됨. 여기에서 cleanup

(database connection)이 처리될 수 있음. (Call jspDestroy)

8.6 Implicit Object

implicit

object Type Purpose Scope

out

JspWriter JSP의 output stream에 write할 JspWriter.

PrintWriter와 BufferedWriter의 기능들을 갖고 있으나,

PrintWriter와 달리 IOException을 throw함.

flush, int getBufferSize()

page

response HttpServletResponse Sub of ServletResponse page

request HttpServletRequest Sub of ServletRequest request

page implementation class Equivalent servlet instance “this” page

session HttpSession Http protocol에 대해서만 valid.

request.getSession().

session

application

ServletContext GenericServlet.getServletContext().

servlet engine의 resource들에의 access를 제공

(resources, attributes, init cotext parameters, request

dispatcher, server info, URL & MIME resources ).

applicati

on

pageContext

PageContext Environment for this page.

이 page와 관련된 모든 scope들에의 접근을 제공.

Container가 error page들과 include/forward page들의

parameter등을 처리.

page에 사용된 object들에 대한 reference들, impleme

ntation-dependent features들을 저장할 context.

page

exception Throwable error page 호출로 가는 uncaught Throwable. page

Page 29: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

config ServletConfig Servlet instance에 specific 함

GenericServlet.getServletConfig().

page

8.7 Sciptlet Syntax.

8.7.1 Conditional statement

8.7.2 Iteration statement

Page 30: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

9 Reusable Web Component.

9.1 include Directive

? <%@include file=”relativeURLspec“ %>

? Included되는 file은 container가 접근 가능해야함.

? translation time에 정의된 resource의 text를 parsing을 하고, include함.

? include되는 file 도 처리될 element들을 가질 수 있음.

? resource를 static object로 간주하여 JSP page안에 있는 byte들이 include됨.

9.2 include Action

? <jsp:include page=”urlSpec” flush==”true|false” />

? <jsp:include page=”urlSpec” flush==”true|false”>

{<jsp:param name=”…” value=”…”|<%= … %> />}*

</jsp:include>

? 현 page와 같은 context내의 static과 dynamic한 resource들의 inclusion을 제공함.

? 내용은 parsing되지 않은 상태로 including됨.

? resource를 dynamic object로 간주하여, 그 object로 request가 보내져서 처리 결과가

include됨.

? 예 : <jsp:include page=”/company/copyright.html” />

Page 31: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

10 JavaBeans

10.1 <jsp:useBean>

10.1.1 Syntax

? <jsp:useBean id =”name” scope=”page|request|session|application” typeSpec />

typeSpec ::= class =”className” ||

type=”typeName” ||

class=”className” type=”typeName” ||

beanName=”beanName” type=”typeName” ||

type=”typeName” beanName =”beanName”

1. 적어도 type과 class중에 하나가 존재해야 함.

2. class와 beanName 둘다 제공하는 것은 invalid.

? id

1. 정의된 scope의 namespace안에서 object instance와 그 object reference로 선언

되고 초기화된 scripting variable name을 identify하는 데 사용할 name.

2. case-sensitive, scripting language의 variable -naming convetion.

? scope : reference가 사용가능한 scope. Default는 page.

? class

1. fully qualified name, case-sensitive.

2. specified된 class는 public no-args constructor를 가지고 있어야 함.

? beanName

1. java.beans.Beans class의 instantiate() method에서 기대하는 Bean의 name.

2. value로 request-time attribute expression을 받을 수 있음.

? type

1. scripting variable이 정의되는 type을 정의. Bean이 casting됨. type은 class 자

신이거나 superclass 또는 implement된 interface.

2. type과 class가 존재하면, class가 type에 할당될 수 있어야 함.

=> 할당될 수 없으면, translation-time error.

3. Referenced된 object는 이 type이 아니면, request time에 scripting variable에

referenced된 object를 할당하려 할 때, java.lang.ClassCastException.

4. specified되지 않으면, class attribute와 같은 값을 가짐.

? jsp:useBean action은 semantic 들이 주어지는 attribute들에 의존하므로, 매우 유연함.

기본 semantic 은 id와 scope를 사용하여 존재하는 object를 찾으려고 함. Object가

발견되지 않으면, 다른 attribute들을 사용하여 object를 생성하려고 함.

? class와 beanName이 없고 type만 있으면, bean은 생성되지 않으므로, scope에 이미

bean이 존재해야 함.

=> 다른 JSP page나 Servlet에서 사용된 object에 local name을 주는데 사용.

? Scriptlets, Expressions, Custom tag들을 사용하여 access 가능.

10.1.2 with Body

Page 32: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? <jsp:useBean id =”name” scope=”page|request|session|application”>

body

</jsp:useBean>

1. action에 표시된 Bean이 생성될 때만, body부분이 호출됨 : one -time initialization.

2. body는 새로 생성된 object를 modify하는데 쓰이는 scriptlet들이나

jsp:setProperty tag들을 포함하지만, body의 내용에는 제한이 없음.

10.1.3 예

? <jsp:useBean id=”connection” class=”com.myco.myapp.Connection” />

? com.myco.myapp.Connecion type의 “connection”이라는 name을 가진 Bean이 이미

생성되어 있는 것을 찾거나 지금 새로 생성됨으로써 이후의 action들에서 사용 가능.

10.2 <jsp:setProperty>, <jsp:getProperty>

10.2.1 <jsp:setProperty>

? Syntax.

<jsp:setProperty name =”beanName” prop_expr />

prop_expr ::= property=”*” |

property=”propertyName” |

property=”propertyNmae” param=”parameterName” |

property=”propertyName” value =”propertyValue”

propertyValue ::= String.

1. value와 param을 동시에 쓸 수 없음.

2. property value가 String이면, target property type으로 변환됨.

? 예.

1. <jsp:setProperty name =”user” property=”*” />

: 모든 request parameter들이 matching되는 “user” bean의 property들로 set.

2. <jsp:setProperty name =”user” property=”name” param=”username” />

: request parameter “username”이 “user” bean의 “name” property로 set.

3. <jsp:setProperty name =”user” property=”name” />

: request parameter “name”이 “user” bean의 “name” property로 set.

4. <jsp:setProperty name =”results” property=”row” value =”<%=i+1 %>” />

10.2.2 <jsp:getProperty>

? <jsp:getProperty name =”user” property=”name” /> == <%=user.getName() %>

10.3 JSP & Servlet Scope

Bean Scope Servlet Scope

request HttpServletRequest

session HttpSession

HttpServletRequest.getSession()

application ServletContext

GenericServlet.getServletContext()

GenericServlet.getServletConfig().getServletContext()

Page 33: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

11 Custom Tag.

11.1 Step 1 : Tag Handler (java file)

11.1.1 Tag Hierarchy

? BodyTag interface -> IterationTag interface -> Tag interface.

? TagSupport class -> Ite rationTag interface

? BodyTagSupport class -> BodyTag interface

11.1.2 javax.servlet.jsp.tagext.Tag interface

? Tag Handler와 implementation class 사이의 기본 protocol을 정의.

? Life cycle과 start, end tag에서 호출될 method들을 정의.

? void setPageContext(PageContext pc)

1. PageContext가 tag handler에 사용가능하도록 doStartTag()보다 먼저 call됨.

? void setParent(Tag t) : doStartTag()보다 먼저 call됨.

? int Tag.doStartTag() throws JspException : tag를 처음 만났을 때, 호출됨.

1. empty action이면, SKIP_BODY를 return해야 함.

2. Non-empty action이면, SKIP_BODY 또는 EVAL_BODY_INCLUDE를 return.

3. SKIP_BODY가 return되면, body는 evaluated되지 않음.

4. EVAL_BODY_INCLUDE가 return되면, body는 evaluated되어 현재의 out으로 감.

? doEndTag() : end tag에 도착하면, 호출됨.

1. EVAL_PAGE를 return하면, page의 나머지 evaluation이 계속됨.

2. SKIP_PAGE를 return하면, page의 나머지는 evaluated되지 않고, request는 완료

됨. 이 request가 forwarding되었거나 included된 것이라면, 현 page evaluation만

완료됨.

? void Tag.release()

1. garbage collection을 위해 state를 release.

2. compiler는 이 method가 모든 tag handler들에서 call될 것임을 보장.

3. doStartTag와 doEndTag 사이에서 multiple 호출이 있을 수 있음.

4. tag handler에 의해 생성된 모든 object들을 release하고, super.release()를 call.

11.1.3 IterationTag interface

? int IterationTag.doAfterBody() throws JspException

1. IterationTag interface를 implement하는 경우, custom tag의 body가 완료되면, 호

출됨.

2. EVAL_BODY_AGAIN을 return하면, body의 새로운 evaluation이 발생. (또다른

doAfterBody()의 호출로 이어짐).

3. SKIP_BODY를 return하면, body evaluation은 더 이상 일어나지 않고, out의

value는 pageContext의 popBody method를 사용하여 회복되며, 그리고나서

doEndTag()가 호출됨.

11.1.4 BodyTag interface

? void BodyTag.setBodyContent(BodyContent bc)

Page 34: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

1. body evaluation이 없으면, 호출되지 않음.

? void BodyTag.doInitBody() throws JspException

1. page implementation에 의한 action 호출당 한번 call됨.

2. setBodyContent() call후, body evaluation전에 call됨.

3. body evaluation이 없으면, 호출되지 않음.

11.1.5 BodyTagSupport Class

? BodyContent BodyTagSupport.getBodyContent()

1. String BodyContent.getString () : body evaluation을 String으로 return.

? JspWriter BodyTagSupport.getPreviousOut() : surrounding out을 얻음.

1. getPreviousOut().print(getBodyContent().getString ())

1) body output to surrounding out

11.1.6 Valid Return Values. (EVAL_BODY는 없음).

doStart doAfterBody doEndTag

EVAL_BODY_INCLUDE All

EVAL_BODY_BUFFEDRED BodyTag only

EVAL_BODY_AGAIN Iteration

SKIP_BODY All All

EVAL_BODY_TAG Deprecated

EVAL_PAGE All

SKIP_PAGE All

? BodyTag.EVAL_BODY_BUFFEDRED

1. 이 tag의 body를 evaluate하는 새로운 버퍼, BodyContent의 생성을 요구함.

? EVAL_BODY_AGAIN은 deprecated된 EVAL_BODY_TAG와 값이 같음.

11.1.7 Outer Tag.

? static final Tag TagSupport. findAncestorWithClass(Tag from, Class c)

1. instance에 가장 가까운 class type의 instance를 찾음.

2. Tag.getParent()를 사용함.

3. Cooperation tag들 사이에서의 coordination을 위해 쓰임.

? Tag Tag.getParent() : tag handler에 가장 가까운 parent를 얻음.

11.1.8 PageContext instance

? JSP page에 연관된 모든 namespace들에 대한 access를 제공.

? convenient access to implicit objects

1. PageContext.getOut() : javax.servlet.jsp.JspWriter

2. PageContext.getRequest().getAttribute(“attrName”);

3. getException(), getPage(), getResponse(), getSession(), getServletConfig (),

getServletContext().

? forwarding, inclusion and error handling

1. forward (), include(), handlePageException().

? JSP page’s attributes.

Page 35: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

1. abstract Object PageContext.findAttribute(String name)

1) page > request > session (if valid) > application 의 순서에 따른 scope로

attribute에 대한 value를 찾아서 return.

2. abstract Enumeration PageContext.getAttributeNamesInScope(int scope)

1) 주어진 scope에서의 모든 attribute들을 enumerate하여 return.

11.2 Step 2 : Tag Library Descriptor (tld file) - <taglib>, <listener>, <tag>,

<attribute>

11.2.1 <taglib>

? <!ELEMENT taglib (tlib-version, jsp-version, short-name, uri?, display-name?,

small-icon?, large-icon?, description?, validator?, listener* , tag+) >

11.2.2 <tag>

? <!ELEMENT tag (name, tag-class, tei-class?, body-content? , display-name?,

small-icon?, large-icon?, description?, variable*, attribute*, example?)>

? <tag-class>

1. javax.servlet.jsp.tagext.Tag interface를 implement하는 tag handler class.

2. Fully qualified Java class name.

? <tei-class>

1. javax.servlet.jsp.tagext.TagExtraInfo의 subclass.

2. Fully qulified Java class name.

? <body-content>

1. tag가 받는 content의 type.

2. 기본적으로 page compositio n tool들에서의 사용을 위함.

3. 현재 3개의 value가 specified됨. : default는 JSP.

1) tagdependent : action의 body는 거의 대부분 다른 language인(eg. embedded

SQL statements) tag handler에 의해 해석되기 위해 그대로 통과함. body는 비

어 있을 수 있음.

2) JSP : action의 body가 JSP syntax를 사용하는 element들을 가짐. body는 비어

있을 수 있음.

3) empty : body는 비어있어야 함.

? <!ELEMENT attribute (name, required?, rtexprvalue?, type?, description?)>

1. <name> : canonical name.

2. <required>

1) nesting attribute의 필수/선택을 정의.

2) Value는 true | false | yes | no. default는 “false”.

3. <rtexprvalue >

1) nesting attribute가 value로 scriptlet expression들을 가질 수 있는지 정의함.

2) Attribute value가 request time에 dynamically 계산될 수 있게 됨.

3) Value는 true | false | yes | no. default는 “false”, 즉 static.

4. <type>

Page 36: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

1) attribute value의 Java type을 정의함.

2) Translation time에 결정되는 static value 들에 대해서 type은 항상 String.

3) rtexprvalue element가 true이면, type은 이 attribute의 value로 specified된

scriptlet expression으로부터의 return type을 정의함.

4) Fully qualified Java class name.

5. 예.

<attribute>

<name>username</name>

<rtexprvalue>true</rtexprvalue>

<required>false</required>

<type>java.lang.String</type>

</attribute>

11.3 Step 3 : DD (web.xml) - <taglib>

11.3.1 <taglib>

? <!ELEMENT taglib (taglib-uri, taglib-location)>

? URI들과 TLD resource path들 사이의 mapping.

? <taglib-uri> : absolute or relative.

11.3.2 예.

<taglib>

<taglib-uri>/myPRlibrary</taglib-uri>

<taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib -location>

</taglib>

11.4 Step 4 : taglib Directive (jsp page) - <%@taglib …%>

? jsp page가 tag library를 사용함을 선언.

? uri

1. tag library를 uniquely identify. Relative 가능.

2. uri는 web.xml에서 정의될 수도 있고, 직접 tld 파일을 지정할 수도 있음.

? action들의 사용을 구별하는 tag prefix를 library에 연관시킴.

? 예 : <%@taglib uri=”/myPRlibrary” prefix=”x” %>

11.5 Step 5 : Using Custom Tag (jsp page) - <prefix:tagname>

? <x:sample /> or <x:sample></x:sample> : empty custom tag

? <x:sample rows=”3” name=”someValue” /> : custom tag with attributes

? <x:sample> some JSP code as the body</x:sample> : surrounding JSP code

? <x:sample><x:if>some condition</x:if></x:sample> : nested custom tags

Page 37: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

12 J2EE Design Pattern.

12.1 Value Objects : coarse-grained view of remote, fine-grained data

12.1.1 장점.

? Remote object의 caching proxy로서 작용하여 network traffic 을 감소시킴.

? Value Object로 표현된 data가 Value Object instance로 client에서 cache되기 때문에,

remote object의 총 load가 감소함.

? Value Object들의 property들에 대한 모든 access들은 local이고, remote method

invocation들을 하지 않음.

? response time을 향상시킴.

12.1.2 단점 : 시시각각 변하는 data에는 맞지 않음. (예. 주식)

12.2 MVC

12.2.1 장점

? data modeling을 data display와 interaction으로부터 분리함으로써 디자인 명료화.

? 같은 data 가 multiple user들에게 다양한 방식으로 보이는 것을 허용.

? 단순화하는 impact analysis 에 의해서 확장성을 향상.

? Well-known API들의 뒤로 application을 encapsulating하고, code 복사를 줄임으로써

maintainability를 향상.

? Application functionality를 presentation으로부터 떼어놓음으로써 reusability 향상.

? MVC boundary들이 자연스런 분산 interface point들이기 때문에, application들을 분산

하기 쉬움.

? 분할 deployment를 사용할 수 있게하고, imcremental update를 가능하게 함.

? Functional consistency에 관한 명료한 디자인에 의해 testability를 용이하게 함.

? Data model, user interaction, 그리고 data display가 “pluggable”하게 되어 있으므로,

flexibility를 향상.

12.3 DataAccessObject

12.3.1 장점

? deployment flexibility가 더 커짐.

? resource vendor independence, resource implementation independence

? CMP로의 migration이 쉬움.

? 향상된 extensibility

12.3.2 단점 : 간접 level때문에 복잡성 증가.

12.4 Business Delegate

12.4.1 장점

? presentation-tier와 business service사이의 coupling의 감소

? manageability 향상 (client-side business abstraction).

? Service exception translation

? Simpler, uniform interface. Performance impact

12.4.2 단점 : 간접 level때문에 복잡성 증가.

Page 38: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

12.5 Other Patterns

12.5.1 Front Component

? request들의 centralized dispatching을 제공. (예. Controller servlet)

? security, navigation, presentation formatting의 centralized handling을 가능하게 함.

12.5.2 Facade

? Client와 subsystem들 사이에 layer를 제공하여, subsystem들을 사용하기 쉽도록 함.

12.5.3 Factory : Object 생성에 대한 request들을 처리.

12.5.4 Singleton : 많아야 하나의 instance를 가질 수 있는 class.

12.5.5 Template Method : Algorithm은 parent class에서 정의, subclass들에서는 그 step들

을 구현.

12.5.6 Bimodal(이중모드) Data Access

? Application이 상황에 따라 data consistency와 access efficiency중에서 선택할 수 있

도록 함. JDBC provides read -only, potentially dirty reads of lists of objects,

bypassing the functionality, and the overhead, of Entity enterprise beans. At the

same time, Entity enterprise beans can still be used for transactional access to

enterprise data.

12.5.7 Session Entity Facade

? Being an instance of the Facade pattern, this pattern shares its applicability. In the

context of J2EE application development, use the Session Facade pattern when

you want to provide a simple interface to a complex subsystem of enterprise

beans or when you want to reduce communication & dependencies b/w client

objects and enterprise beans.

Page 39: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

제 3 장. Design Pattern 상세.

1 Value Objects

1.1 Context

1.1.1 Application clients는 enterprise beans 와 data를 교환할 필요가 있음.

1.2 Problem

1.2.1 Session bean & Entity bean

? J2EE application들은 session bean들과 entity bean들로써 server-side business

component들을 구현함.

? Session bean들은 business service들을 나타내고, client와의 one -to-one 관계를 유지

함. Entity bean들은 반대로, multi-user이고, persistent data를 나타내는 transactional

object들임.

? Session bean : Session Facade pattern 마다 구현되었을 때, coarse-grained service

method들을 제공. 그 service method들 중의 어떤 것은 method들을 호출한 client에

게 data 를 return. 그런 경우에는 client는 모든 attribute value들에 대한 값을 얻을 때

까지 여러 번 session bean의 get method들을 호출해야 함.

? Entity bean : 지속적인 business component들을 구현. Entity bean은 각 attribute에

대해 accessor method(get method)를 제공함으로써 attribute 들의 value들을 보여줌.

Client가 entity bean으로부터 data value를 필요로 할 때, entity bean의 get method를

필요로 하는 모든 attribute에 대한 data를 얻을 때까지 여러 번 호출할 수 있음.

1.2.2 Network Overhead

? EJB application에서 session bean 또는 entity bean에의 각 호출은 bean에의 client의

근접에 관계없이 network layer를 활용하는, 잠정적으로 remote method invocation.

그런 enterprise bean들에의 호출들은 network에 overhead를 만듬.

? remote method들의 사용이 증가함에 따라, application performance는 심각하게 떨어

지므로, single attribute value들을 return하는 get method들을 multiple call하는 것은

enterprise bean으로부터 data value들을 얻는데 비능률적임.

? Enterprise bean method call들은 entity bean을 hold하고 있는 client와 EJB container

가 둘다 같은 JVM, OS, 또는 physical machine에서 실행되고 있더라도, system의

network layer들을 통과할 수도 있음.

? 어떤 vendor들은 direct access approach를 더 사용함으로써 이 overhead를 줄일 수

있음.

1.3 Forces

? J2EE application들은 enterprise bean component들로 business component들을 구현

함. Enterprise bean에의 모든 access는 bean으로의 remote interface들을 통해 이루어

짐. Enterprise bean에의 모든 call은 잠정적으로 network overhead를 갖는 remote

method call.

? 전형적으로, application들은 update 처리보다 read 처리의 빈도가 많음.

Page 40: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? Client는 일반적으로 enterprise bean의 하나 이상의 attribute value를 요구함. Client는

enterprise bean에 의존적인 object들에 대한 value들을 필요로 할 수 있음. 그러므로,

client는 요구되는 data를 얻기 위해서 multiple remote call들을 호출할 수 있음.

? Enterprise bean에 대한 client의 call들의 수는 network performance에 영향을 줌.

1.4 Solution

? Business data를 encapsulate하기 위해 Value Object를 사용하라. Single method call

이 Value Object를 보내고 얻기 위해 사용된다. business data를 위한 enterprise bean

을 client가 request했을 때, enterprise bean은 Value Object를 생성하여 attribute

value들로 채우고, client로 전달할 수 있다.

? client들은 일반적으로 enterprise bean으로부터 하나 이상의 value를 요구함. Remote

call들의 수를 줄이고 연관된 overhead를 피하기 위해서, enterprise bean에서 client로

data를 전달하기 위해 Value Object들을 사용하는 것이 최선임.

? enterprise bean이 Value Object를 사용할 때, client는 각 attribute value들을 얻기 위

해 많은 remote method call들을 하는 대신에 Value Object를 요구하기 위해

enterprise bean에 single remote method 호출을 함. Enterprise bean은 새로운 value

object instance를 생성하고, attribute들을 새로 만들어진 Value Object에 복사해 넣은

다음, client로 retutrn함.

? Client는 Value Object를 받고, accessor method들을 호출하여 각 attribute value들을

Value Object로부터 얻을 수 있음. Value Object의 구현은 그래서 모든 attributes들을

public으로 만들 수 있음. Value Object는 clent로 passed by value 방식으로 전달되었

기 때문에, Value Object instance에 대한 모든 call들은 remote method 호출대신에

local call.

2 Model-View-Control(MVC).

2.1 Problem : Supporting Multiple Enterprise Clients

? enterprise application들은 multiple interface type들로 multiple type의 user들을 지원

할 필요가 있다. 예로, online store는 web customer들에 대해 HTML, wireless

custormer들에 대해서는 WML, administrator들에 대해서는 JFC/Swing interface,

supplier들에 대해서는 xml-based web service를 필요로 할 수 있다.

Page 41: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? single type의 client를 지원하기 위한 application을 개발할 때는, presentation과

control을 위해서 data access logic 을 interface-specific logic 과 뒤섞는 것이 좋을 수

있음. 하지만, 그런 접근은 각 type의 client interface를 지원하도록 다른 application들

을 개발할 필요가 있는 multiple type의 client들을 지원할 필요가 있는 enterprise

system들에 적용하기에는 부적합함.

? Non-interface-specific code가 각 application에서 중복되고, 결과적으로 testing과

maintenance뿐만 아니라, 종종 copy-and-paste라는 구현에서의 노력의 중복.

Interface-specific과 non-interface-specific code가 뒤얽혀 있기 때문에, 무엇을 복사

할지 결정하는 것 자체도 비용적인 일임.

? 중복 노력들은 불가피하게 불완전함. 천천히, 그러나 확실히, 같은 core functionality를

제공하게 되는 application들은 다른 system들로 진화함.

2.2 Solution

? 이런 비용들을 피하면서 어떻게 multiple type의 client들을 지원할 수 있을까? 같은

enterprise data는 다른 view들로 접근할 필요가 있고, 또 다른 interaction들을 통해

변경될 필요가 있음. Multiple type의 view들과 interaction들을 지원하는 것은

enterprise application의 core functionality를 제공하는 component들에 영향을 주어서

는 안됨. 해답은 Model-View-Controller Architecture를 사용하는 것이다!

? Model-View-Controller (MVC) architecture를 J2EE application에 적용함으로써, core

data access functionality를 이를 사용하는 presentation과 cotrol logic 으로부터 분리함.

그런 분리는 multiple view들이 같은 enterprise data model을 공유할 수 있도록 하여,

multiple client들을 지원하는 것이 구현하고 test하고 유지하기 쉽게 함.

Page 42: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? MVC architecture는 전통적인 입력, 처리, 그리고 출력 task들을 graphical user

interaction model에 mapping하는데 처음으로 적용되었던 Samlltalk에 근원을 가짐. 그

러나, 이들 개념들을 multi-tier enterprise application들에 mapping 하는 것은 단순.

2.3 Model

? Enterprise data와 business rule들(access와 update를 좌우하는)을 표현함.

? 종종 실세계 처리의 software approximation의 역할.

? Model을 정의할 때 단순한 실세계-Modeling 기술이 적용됨.

2.4 View

? Model의 내용들을 표현함.

? Model을 통해 enterprise data 에 access하고, 어떻게 그 data가 표현될지를 specify함.

? Model에 변화가 생겼을 때, consistency를 유지하는 것은 view의 책임임.

? Push model : view를 change notification을 위해 model에 등록.

? Pull model : 최근의 data를 얻을 필요가 있을 때 view에게 model을 call할 책임.

2.5 Controller

? view와의 user interaction들을 model에 의해 수행될 action들로 번역함.

? Stand-alone GUI client에서 user interaction들은 button click이나 menu selection들

이 될 수 있고, web application에서는 GET과 POST HTTP request들로 나타남.

? Model에 의해 수행되는 action들은 business process들을 activating 또는 model의

state를 변화시키는 것을 포함함.

? User interaction들과 model action들의 결과에 기반하여, controller는 적절한 view의

선택으로 응답함.

2.6 MVC architecture의 장점.

2.6.1 Mutiple view들이 같은 model을 사용.

? model과 view의 분리는 같은 enterprise model을 사용하는 multiple view들을 허용함.

Page 43: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

? 결과적으로 enterprise application의 model component들은, model로의 모든 access들

이 이 component들을 거치기 때문에, 구현, test 그리고 유지하기 쉬움.

2.6.2 새로운 type의 client들에 대한 지원이 쉬움.

? 새로운 type의 client들을 지원하기 위해 view와 controller만 만들어 enterprise

model에 연결하면 됨.

3 Data Access Object (DAO).

3.1 Context

? data에의 access는 data의 source에 따라 다양함. Database에 관한 것처럼 persistent

storage에의 access는 storage의 type(RDBMS, OODBMS, flat files등)과 vendor

implementation에 따라 크게 달라짐.

3.2 Problem

? 많은 실세계 J2EE application들은 어떤 점에서 persistent data 를 사용할 필요가 있음.

Persistent storage는 다른 mechanism들로 구현되고, 이에 접근하기 위해 쓰이는 API

들에서 큰 차이들이 있음. 또다른 application들은 다른 system에 있는 data에 접근할

필요가 있을 수 있음. 예로, data는 mainframe, LDAP repository, B2B service, credit

card bureau 등에 있을 수 있음.

? 전형적으로 application들은 persistent data를 표현하는 entity bean들과 같은

persistent하고 공유된 분산 component들을 사용함. Application은 이 entity bean들이

명시적으로 persistent storage들을 접근할 때, 그 entity bean들에 대해 bean-

managed persistence를 채용하도록 고려됨. 즉, entity bean은 persistent storage를 직

접 접근하기 위한 code를 포함함. 더 단순한 요구들의 application은 entity bean들을

사용하여 그리고, 대신에 data를 얻고 변경하기 위해 persistent storage를 직접

access하는데 session bean들이나 servlet들을 사용하여 더 나을 수 있음.

? application들은 RDBMS에 있는 data 를 access하기 위해 JDBC API를 사용할 수 있음.

JDBC API는 relational database와 같은 persistent storage내의 data에 standard

access와 manipulation을 가능하게 함. JDBC는 RDBMS table들에 accessing하기 위한

표준 방법인 SQL statement들을 사용하는 J2EE applicatio n들을 가능하게 함. 그러나,

RDBMS environment내에서도, SQL statement들의 actual syntax와 format은

database에 따라 변할 수 있음.

? 심지어 persistent storage의 다른 type들에 큰 변화가 있었음. API들에 지원을 받는

access mechanism들, 지원되는 API들, 그리고 feaure들은 RDBMS같은 persistent

storage의 relational type을 Object Oriented Databases(OODBMS)들, file system-

based ISAM database들, 또는 단순하게 flat file들과 같은 persistent store들의 다른

type들에 비교했을 때, 크게 변함. Mainframe, CORBA service 또는 B2B service같은

파생된 또는 전혀 다른 system으로부터 data 를 access할 필요가 있는 application들은

종종 독점적일 수 있는 API들을 사용하기를 요구받음. 그런 전혀 다른 data source들은

application들에 어려움을 주고, 잠정적으로 application code와 integration code사이에

강한 integration을 만듬. business component들(entity bean들, session bean들 그리고

Page 44: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

심지어 servlet들과 JSP 같은 presentation component들)이 data source에 access할

필요가 있을 때, connectivity를 이루고, data source를 manipulate하기 위해 적절한

API를 사용할 수 있음. 그러나, connectivity와 data access code를 포함하기 때문에,

이 component들과 data source 구현 사이에 tight coupling을 가져옴. 그런

component들에서의 code dependency들은 한 type의 data source로부터 다른 type으

로 application을 migrate하는 것을 어렵게 함. Data source가 변했을 때, component들

은 새로운 type의 data source를 처리하기 위해 변경해야 할 필요가 있음.

3.3 Forces

? bean-managed entity bean들, session bean들 그리고 servlets/JSP 같은 component들

은 persistent store 들과 다른 legacy system들, B2B, LDAP 등과 같은 data source들

로부터 정보를 얻고 저장할 필요가 있음. Persistent storage API들은 vendor에 따라

변함. 이 API들과 그들의 능력들 또한 storage type에 따라 변함. Legacy system들에

access하는 component들은 전형적으로 독점적인 API들을 사용하여 이루어짐.

? component들의 portability는 specific access mechanism들과 API들이 component들

에 포함되었을 때, 직접적으로 영향받음. Component들은 실제의 persistent store 또는

다른 storage type들과 다른 data source type들로 쉬운 migration을 제공하는 data

source 구현에 전달될 필요가 있음.

3.4 Solution

? Data source에의 모든 access를 추상화하고 encapsulate하기 위해 Data Access

Object를 사용하라. Data Access Object는 data를 얻고 저장하기 위해 data source와의

connection을 다룸.

? Data Access Object는 이런 pattern의 기본 object임. DAO는 data source와 협력해야

하는 access mechanism을 구현함. Data source는 RDBMS같은 persistent store와

B2B exchange같은 외부 service, LDAP database같은 repository이거나, CORBA IIOP

또는 low-level socket들을 통해 접근되는 business service일 수 있음. DAO는 client

들로부터 세세한 data source 구현을 숨김. Underlying data source 구현이 변해도

client에의 DAO에 의해 노출된 단순화한 interface는 변하지 않기 때문에, 이 pattern

은 DAO가 client들 또는 business component들에 영향없이 다른 storage scheme들에

적용될 수 있게 함.

4 Business Delegate.

4.1 Context

? System은 종종 network을 통해 전체 business service API를 client들에 노출시킴.

4.2 Problem

? Presentation-tier component들은 business service들과 직접적으로 interact함. 이

direct interaction은 business service API의 세세한 underlying 구현을 presentation

tier로 노출시킴. 결과로서, presentation-tier component들은 business service들의 구

현에서 변화가 있으면, 또한 바껴야 함.

? 덧붙여, business service API를 사용하는 presentation-tier component들은 network

Page 45: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

으로 너무 많은 호출들을 하기 때문에, network performance에 악영향을 줄 수 있음.

이것은 presentation-tier component들이 underlying API를 client-side의 caching

mechanism 또는 aggregating service없이 직접적으로 사용할 때 발생함.

? 마지막으로, service API들을 client에게 직접적으로 노출시키는 것은 client에게 EJB의

분산성에 관련된 network 문제를 처리하도록 강요함.

4.3 Forces

? Presentation-tier client들은 business service들에 접근할 필요가 있음. 목표는

presentation-tier client들과 business service API 사이에 coupling을 최소화하여, 세

세한 underlying 구현을 숨기는 것임.

? Business service 정보에 대해 caching mechanism을 구현하는 것이 바람직함. Client

와 business servicee들 사이이 network traffic을 줄이는 것이 바람직함. Business

Delegate는 client와 service사이에 불필요한 layer를 첨가하여, 복잡해지고 유동성을

줄이게 됨.

4.4 Solution

? presentation-tier client들과 business service들 사이의 coupling을 줄이기 위해

Business Delegate를 사용하라. Business Delegate 는 EJB archtecture의 세세한 부분

에의 lookup과 access같은 세세한 underlying 구현을 숨긴다.

? Business Delegate는 client-side business abstraction으로 동작함. 구현 전략에 따라

서는, Business Delegate는 client들을 business service API의 구현에서의 가능한

volatility로부터 보호할 수 있음. 잠재적으로, 이것은 business service API 또는

underlying 구현이 변했을 때, presentation-tier client code의 변경을 감소시킴. 하지

만, business service API가 바뀌면, 그래도 수정이 필요할 수 있음.

? 장점은 세세한 underlying service를 숨기는 것임. 예로, client는 naming과 lookup

service들에 투명할 수 있음. 또한, Business Delegate는 business service level

exception들을 가로채서, 대신에 application level exception들을 만들 수 있음.

? 다른 장점은 delegate가 결과들을 cache할 수도 있다는 것임. Caching 된 결과들은 불

필요하고 잠재적으로 부담이 되는 network에서의 round trip들을 제한하기 때문에

performance를 상당히 향상시킬 수 있음.

? Business Delegate는 Lookup Service로 불리는 component를 사용함. Lookup Service

는 business service lookup code의 세세한 underlying 구현을 숨길 책임이 있음.

Lookup Service는 delegate의 일부로 만들 수도 있지만, Service Locator(SJC) pattern

에서 설명된 대로 별도의 component로 구현되는 것이 추천됨.

? Business Delegate가 Session 외관으로 사용될 때, 전형적으로 둘 사이에는 1-1

relationship이 있음. 1-1 relationship은, 1-many relationship을 만들면서 multiple

business service들과의 interaction에 관계되는 Business Delegate에 encapsulated되

어 있을수 있는 logic이 종종 Session 외관으로 행동하기 때문에, 존재함.

? 마지막으로, 단순히 presentation과 business tier들 사이가 아닌, 다른 tier들 사이의

coupling을 줄이는 데 사용될 수 있음.

Page 46: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

제 4 장. 참고 자료.

1 Servlet API

1.1 Servlet Interface

init(ServletConfig) Called by the servlet container to indicate to a servlet that the servlet is

being placed into service.

destroy() Called by the servlet container to indicate to a servlet that the servlet is

being taken out of service.

service(ServletRequest,

ServletResponse)

Called by the servlet container to allow the servlet to respond to a request.

ServletConfig getServletConfig() Returns a ServletConfig object, which contains initialization and startup

parameters for this servlet.

String getServletInfo Returns information about the servlet, such as author, version, and

copyright.

1.2 ServletConfig Interface

String getInitParameter(String) Returns a String containing the value of the named initialization parameter,

or null if the parameter does not exist.

Enumeration

getInitParameterNames()

Returns the names of the servlet's initialization parameters as an

Enumeration of String objects, or an empty Enumeration if the servlet has

no initialization parameters.

ServletContext

getServletContext()

Returns a reference to the ServletContext in which the caller is executing.

String getServletName () Returns the name of this servlet instance. The name may be provided via

server administration, assigned in the web application deployment

descriptor, or for an unregistered (and thus unnamed) servlet instance it

will be the servlet's class name.

1.3 ServletContext Interface

String getInitParameter(String) Returns a String containing the value of the named context-wide

initialization parameter, or null if the parameter does not exist.

Enumeration

getInitParameterNames()

Returns the names of the context's initialization parameters as an

Enumeration of String objects, or an empty Enumeration if the context has

no initialization parameters.

Object getAttribute (String) Returns the servlet container attribute with the given name, or null if there

is no attribute by that name.

setAttribute(String, Object) Binds an object to a given attribute name in this servlet context.

removeAttribute (String) Removes the attribute with the given name from the servlet context.

Page 47: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

Enumeration getAttributeNames () Returns an Enumeration containing the attribute names available within this

servlet context.

log(String) Writes the specified message to a servlet log file, usually an event log.

log(String, Throwable) Writes an explanatory message and a stack trace for a given Throwable

exception to the servlet log file.

ServletContext getContext(String

uripath)

Returns a ServletContext object that corresponds to a specified URL on the

server. The given path must be absolute (beginning with "/") and is

interpreted based on the server's document root.

String getRealPath(String path) Returns a String containing the real path for a given virtual path.

URL getResource(String path) Returns a URL to the resource that is mapped to a specified path. The path

must begin with a "/" and is interpreted as relative to the current context

root.

This method allows the servlet container to make a resource available to

servlets from any source. Resources can be located on a local or remote

file system, in a database, or in a .war file. The resource content is

returned directly, so be aware that requesting a .jsp page returns the JSP

source code. Use a RequestDispatcher instead to include results of an

execution. This method has a different purpose than

java.lang.Class.getResource, which looks up resources based on a class

loader. This method does not use class loaders.

InputStream

getResourceAsStream(String path)

Returns the resource located at the named path as an InputStream object.

RequestDispatcher

getRequestDispatcher(String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource

located at the given path. The resource can be dynamic or static. The

pathname must begin with a "/" and is interpreted as relative to the current

context root. Use getContext to obtain a RequestDispatcher for resources

in foreign contexts. This method returns null if the ServletContext cannot

return a RequestDispatcher.

RequestDispatcher

getNamedDispatcher(String name)

Returns a RequestDispatcher object that acts as a wrapper for the named

servlet.

1.4 ServletRequest Interface

Object getAttribute (String) Returns the value of the named attribute as an Object, or null if no

attribute of the given name exists.

setAttribute(String, Object) Stores an attribute in this request.

removeAttribute (String) Removes an attribute from this request.

Page 48: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

Enumeration getAttributeNames () Returns an Enumeration containing the names of the attributes available to

this request. This method returns an empty Enumeration if the request has

no attributes available to it.

String getParameter(String) Returns the value of a request parameter as a String, or null if the

parameter does not exist.

String[] getParameterValues (String) Returns an array of String objects containing all of the values the given

request parameter has, or null if the parameter does not exist.

Enumeration getParameterNames() Returns an Enumeration of String objects containing the names of the

parameters contained in this request.

ServletInputStream

getInputStream()

Retrieves the body of the request as binary data using a

ServletInputStream. Either this method or getReader() may be called to

read the body, not both.

BufferedReader getReader() Retrieves the body of the request as character data using a

BufferedReader. The reader translates the character data according to the

character encoding used on the body.

Either this method or getInputStream() may be called to read the body, not

both.

RequestDispatcher

getRequestDispatcher(String path)

Returns a RequestDispatcher object that acts as a wrapper for the

resource located at the given path. A RequestDispatcher object can be

used to forward a request to the resource or to include the resource in a

response. The resource can be dynamic or static.

The pathname specified may be relative, although it cannot extend outside

the current servlet context. If the path begins with a "/ " it is interpreted as

relative to the current context root. This method returns null if the servlet

container cannot return a RequestDispatcher.

The difference between this method and ServletContext’s method is that

this method can take a relative path.

String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent the

request.

String getRemoteHost() Returns the fully qualified name of the client that sent the request, or the

IP address of the client if the name cannot be determined.

String getServerName () Returns the host name of the server that received the request.

int getServerPort() Returns the port number on which this request was received.

String getProtocol() Returns the name and version of the protocol the request uses in the form

protocol/majorVersion.minorVersion, for example, HTTP/1.1.

String getScheme () Returns the name of the scheme used to make this request, for example,

http, https, or ftp.

Page 49: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

boolean isSecure() Returns a boolean indicating whether this request was made using a

secure channel, such as HTTPS.

String getContentType() Returns the MIME type of the body of the request, or null if the type is not

known.

int getContentLength() Returns the length, in bytes, of the request body and made available by

the input stream, or -1 if the length is not known.

String getCharecterEncoding () Returns the name of the character encoding used in the body of this

request.

setCharecterEncoding(String) Overrides the name of the character encoding used in the body of this

request.

1.5 ServletResponse Interface

ServletOutputStream

getOutputStream()

Returns a ServletOutputStream suitable for writing binary data in the

response. The servlet container does not encode the binary data. Calling

flush() on the ServletOutputStream commits the response. Either this

method or getWriter() may be called to write the body, not both

PrintWriter getWriter() Returns a PrintWriter object that can send character text to the client. The

character encoding used is the one specified in the charset= property of

the setContentType method, which must be called before calling this

method for the charset to take effect.

Calling flush() on the PrintWriter commits the response.

Either this method or getOutputStream may be called to write the body,

not both.

setContentType(String type) Sets the content type of the response being sent to the client. The content

type may include the type of character encoding used, for example,

text/html;charset=ISO-8859-1.

If obtaining a PrintWriter, this method should be called first.

setContentLength(int) Sets the length of the content body in the response. In HTTP servlets, this

method sets the HTTP Content-Length header.

boolean isCommitted() Returns a boolean indicating if the response has been committed. A

commited response has already had its status code and headers written.

reset() Clears any data that exists in the buffer as well as the status code and

headers. If the response has been committed, this method throws an

IllegalStateException.

int getBufferSize() Returns the actual buffer size used for the response. If no buffering is

used, this method returns 0.

setBufferSize(int) Sets the preferred buffer size for the body of the response.

This method must be called before any response body content is written;

if content has been written, this method throws an IllegalStateException.

Page 50: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

flushBuffer() Forces any content in the buffer to be written to the client. A call to this

method automatically commits the response, meaning the status code and

headers will be w ritten.

resetBuffer() Clears the content of the underlying buffer in the response without

clearing headers or status code. If the response has been committed, this

method throws an IllegalStateException.

1.6 abstract class GenericServlet implements Servlet, ServletConfig,

Serializable

init() A convenience method which can be overridden so that there's no need to

call super.init(config).

log(String) Writes the specified message to a servlet log file, prepended by the

servlet's name.

log(String, Throwable) Writes an explanatory message and a stack trace for a given Throwable

exception to the servlet log file, prepended by the servlet's name.

abstract service() Called by the servlet container to allow the servlet to respond to a

request.

This method is declared abstract so subclasses, such as HttpServlet, must

override it.

1.7 abstract class HttpServlet extends GenericServlet

Eventhough this class is abstract it provides empty implementations of all methods.

Typically servlets extending this class would override one of the doXXX methods.

public service(ServletRequest,

ServletResponse)

Dispatches client requests to the protected service method. There's no

need to override this method.

protected

service(HttpServletRequest,

HttpServletResponse)

Receives standard HTTP requests from the public service method and

dispatches them to the doXXX methods defined in this class.

There's no need to override this method.

doGet(HttpServletRequest,

HttpServletResponse)

Should be safe and idempotent (repeatable)

Override to service GET requests. HEAD requests are also satisfied since

doHead internally uses this method with a specialized response.

doPost(HttpServletRequest,

HttpServletResponse)

Need not be safe or idempotent.

Override to service POST requests.

doPut(), doDelete(), doHead (),

doTrace(), doOptions ()

These methods are not common and service the corresponding requests.

long getLastModified() Returns the time the HttpServletRequest object was last modified

1.8 HttpServletRequest Interface

Page 51: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

String getHeader(String) Returns the value of the specified request header as a String. If the

request did not include a header of the specified name, this method

returns null. The header name is case insensitive. You can use this method

with any request header.

Enumeration getHeaders(String) Returns all the values of the specified request header as an Enumeration

of String objects. If the request did not include any headers of the

specified name, this method returns an empty Enumeration. The header

name is case insensitive. You can use this method with any request

header.

Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains. If

the request has no headers, this method returns an empty enumeration.

int getIntHeader(String) Returns the value of the specified request header as an int. If the request

does not have a header of the specified name, this method returns -1. If

the header cannot be converted to an integer, this method throws a

NumberFormatException.

long getDateHeader(String) Returns the value of the specified request header as a long value that

represents a Date object. Use this method with headers that contain dates,

such as If-Modified-Since. If the request did not have a header of the

specified name, this method returns -1.

Cookie[] getCookies () Returns an array containing all of the Cookie objects the client sent with

this request, or null if no cookies sent.

HttpSession getSession([boolean

create])

Returns the current HttpSession associated with this request or, if if there

is no current session and create is true(default), returns a new session.

String getRequestURI() Returns the part of this request's URL from the protocol name up to the

query string in the first line of the HTTP request.

requestURI = contextPath + servletPath + pathInfo

String getContextPath() Returns the portion of the request URI that indicates the context of the

request. The context path always comes first in a request URI. The path

starts with a "/" character but does not end with a "/" character. For

servlets in the default (root) context, this method returns "".

String getServletPath() Returns the part of this request's URL that calls the servlet. This includes

either the servlet name or a path to the servlet, but does not include any

extra path information or a query string.

String getPathInfo () Returns any extra path information associated with the URL the client sent

when it made this request. The extra path information follows the servlet

path but precedes the query string. This method returns null if there was

no extra path information.

String getPathTranslated() Returns any extra path information after the servlet name but before the

query string, and translates it to a real path.

Page 52: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

String getQueryString () Returns the query string that is contained in the request URL after the

path.

String getMethod() Returns the name of the HTTP method with which this request was made,

for example, GET, POST, or PUT.

String getAuthType() Returns the name of the authentication scheme used to protect the servlet.

All servlet containers support BASIC_AUTH, FORM_AUTH, and

CLIENT_CERT_AUTH and may support DIGEST_AUTH. If the servlet is

not authenticated null is returned.

String getRemoteUser() Returns the login of the user making this request, if the user has been

authenticated, or null if the user has not been authenticated.

Principal getUserPrincipal() Returns a java.security.Principal object containing the name of the current

authenticated user. If the user has not been authenticated, the method

returns null.

boolean isUserInRole (String role) Returns a boolean indicating whether the authenticated user is included in

the specified logical "role". Roles and role membership can be defined

using deployment descriptors. If the user has not been authenticated, the

method returns false.

String getRequestedSessionId () Returns the session ID specified by the client. This may not be the same

as the ID of the actual session in use. For example, if the request specified

an old (expired) session ID and the server has started a new session, this

method gets a new session with a new ID. If the request did not specify a

session ID, this method returns null.

boolean

isRequestedSessionIdValid ()

Checks whether the requested session ID is still valid.

boolean

isRequestedSessionIdFromCookie ()

Checks whether the requested session ID came in as a cookie.

boolean

isRequestedSessionIdFromURL()

Checks whether the requested session ID came in as part of the request

URL.

1.9 HttpServletResponse Interface

addCookie (Cookie) Adds the specified cookie to the response. This method can be called

multiple times to set more than one cookie.

addHeader(String name, String

value)

addIntHeader(String name, int

value)

addDateHeader(String name, long

value)

Add a response header with the given name and String value / integer

value / date value respectively. These methods allow response headers to

have multiple values.

Page 53: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

setHeader(String name, String

value)

setIntHeader(String name, int value)

setDateHeader(String name, long

value)

Set a response header with the given name and String value / integer

value / date value respectively. If the header had already been set, the

new value overwrites the previous one. The containsHeader method can

be used to test for the presence of a header before setting its value.

setStatus (int sc) Sets the status code for this response. This method is used to set the

return status code when there is no error (for example, for the status

codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and the

caller wishes to invoke an error-page defined in the web applicaion, the

sendError method should be used instead.

If this method is called after the response is committed, the call is ignored.

sendError(int sc[, String msg]) Sends an error response to the client using the specified status clearing

the buffer. The server defaults to creating the response to look like an

HTML-formatted server error page, setting the content type to

"text/html", leaving cookies and other headers unmodified. If an error-

page declara tion has been made for the web application corresponding to

the status code passed in, it will be served back in preference to the

suggested msg parameter.

If the response has already been committed, this method throws an

IllegalStateException. After using this method, the response should be

considered to be committed and should not be written to.

sendRedirect(String location) Sends a temporary redirect response to the client using the specified

redirect location URL. This method can accept relative URLs; the servlet

container must convert the relative URL to an absolute URL before

sending the response to the client. If the location is relative without a

leading '/' the container interprets it as relative to the current request URI.

If the location is rela tive with a leading '/' the container interprets it as

relative to the servlet container root.

If the response has already been committed, this method throws an

IllegalStateException. After using this method, the response should be

considered to be committed and should not be written to.

String encodeURL(String url) Encodes the specified URL by including the session ID in it, or, if encoding

is not needed, returns the URL unchanged.

For robust session tracking, all URLs emitted by a servlet should be run

through this method. Otherwise, URL rewriting cannot be used with

browsers which do not support cookies.

Page 54: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

String encodeRedirectURL(String

url)

Encodes the specified URL for use in the sendRedirect method or, if

encoding is not needed, returns the URL unchanged.

All URLs sent to the HttpServletResponse.sendRedirect method should be

run through this method. Otherwise, URL rewriting cannot be used with

browsers which do not support cookies.

1.10 HttpSession Interface

Object getAttribute (String) Returns the object bound with the specified name in this session, or null if

no object is bound under the name.

setAttribute(String, Object) Binds an object to a given attribute name in this session. If an object of the

same name is already bound to the session, the object is replaced.

After this method executes, and if the new object implements

HttpSessionBindingListener, the container calls

HttpSessionBindingListener.valueBound.

If an object was already bound to this session of this name that

implements HttpSessionBindingListener, its

HttpSessionBindingListener.valueUnbound method is called.

removeAttribute (String) Removes the attribute with the given name from the session. After this

method executes, and if the object implements

HttpSessionBindingListener, the container calls

HttpSessionBindingListener.valueUnbound.

Enumeration getAttributeNames () Returns an Enumeration of String objects containing the names of all the

objects bound to this session.

String getId () Returns a string containing the unique identifier assigned to this session.

long getCreationTime () Returns the time when this session was created

long getLastAccessedTime () Returns the last time the client sent a request associated with this session

int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container

will keep this session open between client accesses. After this interval,

the servlet container will invalidate the session. The maximum time

interval can be set with the setMaxInactiveInterval method. A negative

time indicates the session should never timeout.

setMaxInactiveInterval(int) Specifies the time, in seconds, between client requests before the servlet

container will invalidate this session. A negative time indicates the session

should never timeout.

invalidate () Invalidates this session then unbinds any objects bound to it.

isNew() Returns true if the client does not yet know about the session or if the

client chooses not to join the session. For example, if the server used only

cookie-based sess ions, and the client had disabled the use of cookies,

then a session would be new on each request.

Page 55: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

1.11 RequestDispatcher Interface

forward (ServletRequest,

ServletResponse)

Forwards a request from a servlet to another resource (servlet, JSP file,

or HTML file) on the server. This method allows one servlet to do

preliminary processing of a request and another resource to generate the

response. forward should be called before the response has been

committed to the client (before response body output has been flushed). If

the response already has been committed, this method throws an

IllegalStateException. Uncommitted output in the response buffer is

automatically cleared before the forward.

include(ServletRequest,

ServletResponse)

Includes the content of a resource (servlet, JSP page, HTML file) in the

response. In essence, this method enables programmatic server-side

includes.

The ServletResponse object has its path elements and parameters remain

unchanged from the caller's. The included servlet cannot change the

response status code or set headers; any attempt to make a change is

ignored.

1.12 SingleThreadModel Interface

No methods This is a ‘marker’ interface

1.13 ServletContextListener Interface

contextInitialized(ServletContextEv

ent)

contextDestroyed(ServletContextEv

ent)

Implementations of this inte rface receive notifications about changes to

the servlet context of the web application they are part of. To receive

notification events, the implementation class must be configured in the

deployment descriptor for the web application.

1.14 ServletContextAttributeListener Interface

attributeAdded(ServletContextAttrib

uteEvent)

attributeRemoved(ServletContextAtt

ributeEvent)

attributeReplaced(ServletContextAtt

ributeEvent)

Implementations of this interface receive notifications of changes to the

attribute list on the servlet context of a web application. To receive

notification events, the implementation class must be configured in the

deployment descriptor for the web application.

1.15 HttpSessionListener Interface

sessionCreated(HttpSessionEvent) Implementations of this interface are notified of changes to the list of

Page 56: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

sessionDestroyed(HttpSessionEvent

)

active sessions in a web application. To receive notification events, the

implementation class must be configured in the deployment descriptor for

the web application.

1.16 HttpSessionActivationListener Interface

sessionDidActivate(HttpSessionEve

nt)

sessionWillPassivate(HttpSessionEv

ent)

Objects that are bound to a session may listen to container events

notifying them that sessions will be passivated and that session will be

activated. A container that migrates session between VMs or persists

sessions is required to notify all attributes bound to sessions implementing

HttpSessionActivationListener.

1.17 HttpSessionAttributeListener Interface

attributeAdded(HttpSessionBindingE

vent)

attributeRemoved(HttpSessionBindi

ngEvent)

attributeReplaced(HttpSessionBindin

gEvent)

This listener interface can be implemented in order to get notifications of

changes made to sessions within this web application.

1.18 HttpSessionBindingListener Interface

valueBound(HttpSessionBindingEve

nt)

valueUnbound(HttpSessionBindingE

vent)

Causes an object to be notified when it is bound to or unbound from a

session. The object is notified by an HttpSessionBindingEvent object. This

may be as a result of a servlet programmer explicitly unbinding an

attribute from a session, due to a session being invalidated, or die to a

session timing out.

Page 57: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

2 web-app_2_3.dtd 분석.

- SCCD 1기 손수정 -

※ 원본 DTD를 참고해서 같이 보시기 바랍니다.

<!-- web.xml(deployment descriptor) 파일 머리부분의 DOCTYPE 선언부의 내용은 아래와

같아야한다.

<!DOCTYPE web-app PUBLIC

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

-->

<!-- “web-app”는 web.xml 의 시작과 끝을 알려주는 root element이고, 다음 요소들은 다음의 순서와

일치하게 기술되어야한다. -->

<!ELEMENT web-app (1.icon? , 2.display-name?, 3.description? , 4.distributable?, 5.context-param* ,

6.filter* , 7.filter-mapping*, 8.listener* , 9.servlet* , 10.servlet-mapping* , 11.session-config? ,

12.mime -mapping*, 13.welcome-file-list? ,14.error-page*, 15.taglib*, 16.resource-env-ref* ,

17.resource -ref* , 18.security-constraint* , 19.login-config?, 20.security-role*, 21.env-entry*,

22.ejb-ref*, 23.ejb-local-ref* )>

1. <!ELEMENT icon (small-icon?, large-icon?)>

GUI도구에서 부모요소를 나타내기 위한 icon에 대한 참조

<!ELEMENT small-icon (#PCDATA)> → 16X16 pixel icon의 위치 기술(gif, jpeg)

<!ELEMENT large-icon (#PCDATA)> → 32X32 pixel icon의 위치 기술

2. <!ELEMENT display-name (#PCDATA)> : 부모요소의 짧은 이름 기술. GUI도구에서 표현

3.<!ELEMENT description (#PCDATA)> : 부모요소의 설명 기술

4. <!ELEMENT distributable EMPTY>

선언시, 분산된 서블릿 컨테이너에 웹 애플리케이션이 배치될 수 있음을 의미

<distributable/>

5.<context-param>

설명 context 초기화 매개변수를 선언

DTD <!ELEMENT context-param (param-name, param-value, description?)>

<!ELEMENT param-name (#PCDATA)>

<!ELEMENT param-value (#PCDATA)>

<!ELEMENT description (#PCDATA)>

예 <context-param>

<param-name>thisIsMyFirstparam</param-name>

<param-value>3</param-value> → Boolean, Double, Float, Integer, String 가능

</context-param>

Page 58: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

6.<filter> : 필터 선언

DTD <!ELEMENT filter (icon?, filter-name, display-name?, description?, filter-class, init-

param*)>

<!ELEMENT icon (small-icon?, large-icon?)>

<!ELEMENT filter-name (#PCDATA)>

<!ELEMENT display-name (#PCDATA)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT filter-class (#PCDATA)>

<!ELEMENT init-param (param-name, param-value, description?)>

<!ELEMENT param-name (#PCDATA)>

<!ELEMENT param-value (#PCDATA)>

<!ELEMENT description (#PCDATA)>

예 <filter>

<filter-name>Games Filter</filter-name>

<filter-class>filters.StopGamesFilter</filter-class>

<init-param>

<param-name>starthour</param-name>

<param-value>10</param-value>

</init-param>

</filter>

7.<filter-mapping> : 필터를 서블릿이나 URL 세트에 mapping

DTD <!ELEMENT filter-mapping (filter-name, (url-pattern | servlet-name))>

<!ELEMENT filter-name (#PCDATA)>

<!ELEMENT url-pattern (#PCDATA)> or <!ELEMENT servlet-name (#PCDATA)>

예 <filter-mapping>

<filter-name>Games Filter</filter-name>

<url-pattern>FindProd</url-pattern>

</filter-mapping>

8.<listener>

설명 애플리케이션의 listener 등록

DTD <!ELEMENT listener (listener-class)>

<!ELEMENT listener-class (#PCDATA)>

예 <listener><listener-class>CounterListenerExample</listener-class></listener>

9.<servlet>

설명 서블릿을 선언

DTD <!ELEMENT servlet (icon?, servlet-name , display-name?, description?,

(servlet-class | jsp-file), init-param* , load-on-startup? , run-as?, security-role-ref* )>

Page 59: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<!ELEMENT icon (small-icon?, large-icon?)>

<!ELEMENT servlet-name (#PCDATA)>

<!ELEMENT display-name (#PCDATA)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT servlet-class (#PCDATA)> or <!ELEMENT jsp-file (#PCDATA)>

<!ELEMENT init-param (param-name, param-value, description?)>

<!ELEMENT param-name (#PCDATA)>

<!ELEMENT param-value (#PCDATA)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT load -on-startup (#PCDATA)>

→ 애플리케이션이 시작될 때, 서블릿이 로딩되도록 설정

<!ELEMENT run-as (description?, role-name)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

<!ELEMENT security-role-ref (description?, role-name, role-link?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

<!ELEMENT role-link (#PCDATA)>

예 <servlet>

<servlet-name>Time2</servlet-name>

<servlet-class>TimeServlet2</servlet-class> → class 명

<init-param>

<param-name> thisIsMyFirstparam</param-name>

<param-value>1</param-value>

</init-param>

<load-on-startup>1</load-on-startup> → 낮은 값일수록 먼저 loading된다.

<security-role-ref> → 서블릿의 보안 역할 이름 설정

<role -name>abc</role-name>

<role -link>admin</role-link>

</security-role-ref>

</servlet>

10.<servlet-mapping>

설명 서블릿과 URL 패턴을 mapping

DTD <!ELEMENT servlet-mapping (servlet-name , url-pattern)>

<!ELEMENT servlet-name (#PCDATA)>

<!ELEMENT url-pattern (#PCDATA)>

예 <servlet-mapping>

<servlet-name>Time2</servlet-name>

Page 60: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<url-pattern>/Time</url-pattern> → http://localhost:8080/Time 으로 접근가능

</servlet-mapping>

11.<session-config>

설명 웹 애플리케이션의 세션 트레킹을 설정

DTD <!ELEMENT session-config (session-timeout?)>

<!ELEMENT session-timeout (#PCDATA)> → 분단위로 설정

예 <session-config><session-timeout>45</session-timeout></session-config>

12.<mime -mapping>

설명 파일 이름의 확장자와 MIME 타입의 연결 설정

DTD <!ELEMENT mime -mapping (extension, mime-type)>

<!ELEMENT extension (#PCDATA)>

<!ELEMENT mime -type (#PCDATA)>

예 <mime-mapping>

<extension>wml</extension> → wml 파일을 다음과 같은 MIME type으로 전송

<mime -type>text/vnd.wap.wml</mime-type>

</mime-mapping>

13.<welcom-file-list>

설명 브라우저가 웹페이지나 서블릿이 아닌 디렉토리를 요구했을 때, 컨데이너가 브라우저에게

넘겨주기 위해 찾아야할 파일의 목록설정.

DTD <!ELEMENT welcome-file-list (welcome-file+)>

<!ELEMENT welcome-file (#PCDATA)>

예 <welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list>

14.<error-page>

설명 에러 코드나 예외 타입과 웹 애플리케이션의 자원의 위치를 mapping

DTD <!ELEMENT error-page ((error-code | exception-type), location)>

<!ELEMENT error-code (#PCDATA)> or <!ELEMENT exception-type (#PCDATA)>

<!ELEMENT location (#PCDATA)>

예 <error-page>

<error-code>400</error-code>

<location>/400.html</location>

</error-page>

15.<taglib>

설명 JSP 태그 라이브러리를 설정

DTD <!ELEMENT taglib (taglib-uri, taglib-location)>

<!ELEMENT taglib-uri (#PCDATA)> → 태그 라이브러리를 인식하기 위한 URI

Page 61: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<!ELEMENT taglib-location (#PCDATA)> → 태그 라이브러리 기술자 파일(.tld 파일)

예 <taglib>

<taglib -uri>/struts.tld</taglib-uri>

<taglib -location>/WEB-INF/struts.tld</taglib-location>

</taglib>

16.<resource-env-ref>

설명 웹 애플리케이션이 관리 객체를 참조한다는 것을 선언

DTD <!ELEMENT resource-env-ref (description?, resource-env-ref-name ,

resource-env-ref-type)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT resource-env-ref-name (#PCDATA)>

<!ELEMENT resource-env-ref-type (#PCDATA)>

예 <resource-env-ref>

<resource-env-ref-name>jms/StockQueue</resource-env-ref-name>

<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>

</resource-env-ref>

17.<resource-ref>

설명 EJB 컴포넌트나 JDBC DataSource 객체 같은 외부 자원에 대한 웹 애플리케이션의 레퍼런스를

정의

DTD <!ELEMENT resource-ref (description?, res-ref-name, res-type, res-au th ,

res-sharing-scope?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT res -ref-name (#PCDATA)>

<!ELEMENT res -type (#PCDATA)>

<!ELEMENT res -auth (#PCDATA)>

<!ELEMENT res -sharing -scope (#PCDATA)>

예 <resource-ref>

<description>Primary database</description>

<res -ref-name>jdbc/primaryDB</res-ref-name>

<res -ref-type>javax.sql.DataSource</res-ref-type> → 자바 클레스 타입

<res -auth>CONTAINER</res-auth> → CONTAINER or SERVLET

<res -sharing-scope>Shareable</res-sharing-scope> →Shareable or Unshareable

</resource-ref>

18.<security-constraint>

설명 보안제약과 resource collection을 연결시키는데 사용

DTD <!ELEMENT security-constraint (display-name?, web-resource-collection+,

auth-constraint?, user-data-constraint?)>

Page 62: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<!ELEMENT display-name (#PCDATA)>

<!ELEMENT web-resource-collection (web-resource-name, description?,

url-pattern*, http-method*)>

<!ELEMENT web-resource-name (#PCDATA)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT url-pattern (#PCDATA)>

<!ELEMENT http-method (#PCDATA)>

<!ELEMENT auth-constraint (description?, role-name*)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

<!ELEMENT user-data-constraint (description?, transport-guarantee)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT transport-guarantee (#PCDATA)>

예 <security-constraint>

<web -resource-collection>

<web-resource-name>SecretProtection</web-resource-name>

<ur l-pattern>/SalaryServer</url-pattern>

<url-pattern>/Server</url-pattern>

<http -method>GET</http -method>

<http -method>POST</http -method>

</web-resource-collection>

<auth-constraint>

<role -name>manager</role-name>

</auth-constraint>

<user-data-constraint>

<transport -guarantee>CONFIDENTIAL</transport-guarantee>

→ NONE, INTEGRAL, CONFIDENTIAL

</user-data-constraint>

</security-constraint>

19.<login-config>

설명 인증 메소드를 설정하거나 애플리케이션에서 이용되는 영역(realm) 이름 혹은 폼 기반 로그인에

대한 속성 값을 설정

DTD <!ELEMENT login-config (auth-method?, realm-name?, form-login-config?)>

<!ELEMENT auth-method (#PCDATA)>

<!ELEMENT realm-name (#PCDATA)>

<!ELEMENT form-login-config (form-login-page, form-error-page)>

<!ELEMENT form-login-page (#PCDATA)>

<!ELEMENT form-error-page (#PCDATA)>

Page 63: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

예 <login-config>

<auth-method>FORM</auth-method> → BASIC, DIGEST, FORM, CLIENT-CERT

<realm-name>Default</realm-name> → http 기본인증에 쓰이는 영역의 이름 설정

<form -login-config> → 폼 기반 로그인에서 로그인페이지와 에러페이지를 설정

<form -login-page>/login.html</form-login-page>

<form -error-page>/error.html</form-error-page>

</form -login-config>

</login-config>

20.<security-role>

설명 보안 역할을 정의하고 이것은 웹 애플리케이션에 보안제약을 적용한다.

DTD <!ELEMENT security-role (description?, role-name)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

예 <security-role><role-name>manager</role -name></security-role>

21.<env-entry>

설명 java:comp/env 컨텍스트 안의 JNDI 검색을 통한 애플리케이션의 환경 항목을 정의

DTD <!ELEMENT env-entry (description?, env-entry-name, env-entry-value?, env-entry-

type)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT env-entry-name (#PCDATA)>

<!ELEMENT env-entry-value (#PCDATA)>

<!ELEMENT env-entry-type (#PCDATA)>

예 <env-entry>

<description>Send pincode by mail</description>

<env-entry-name>mailPincode</env-entry-name> → 환경항목의 검색이름 설정

<env-entry-value>false</env-entry-value> → 애플리케이션에 기본 설정된 환경항목 값

<env-entry-type>java.lang.Boolean</env-entry-type>

→java.lang.Integer, java.lang.double, java.lang.Float, or java.lang.String

</env-entry>

22.<ejb-ref>

설명 엔터프라이즈 빈즈의 레퍼런스를 정의

DTD <!ELEMENT ejb-ref (description?, ejb-ref-name, ejb-ref-type, home, remote, ejb-link?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT ejb-ref-name (#PCDATA)>

<!ELEMENT ejb-ref-type (#PCDATA)>

<!ELEMENT home (#PCDATA)>

<!ELEMENT remote (#PCDATA)>

Page 64: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<!ELEMENT ejb-link (#PCDATA)>

예 <ejb-ref>

<description>Cruise ship cabin</description>

<ejb -ref-name>ejb/CabinHome</ejb-ref-name>

→서블릿 코드가 EJB 레퍼런스를 얻는데 사용하는 JNDI의 이름

<ejb -ref-type>Entity</ejb-ref-type> → 빈의 타입 : Entity or Session

<home>com.titan.cabin.Cabinhome</home>

→EJB의 홈 인터페이스의 패키지 명을 포함한 이름

<remote>com.titan.cabin.Cabin</remote>

→EJB의 원격 인터페이스의 패키지를 포함한 이름

</ejb-ref>

23.<ejb-local-ref>

설명 지역 엔터프라이즈 빈즈의 레퍼런스를 정의

DTD <!ELEMENT ejb-local-ref (description?, ejb-ref-name, ejb-ref-type, local-home, local,

ejb-link?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT ejb-ref-name (#PCDATA)>

<!ELEMENT ejb-ref-type (#PCDATA)>

<!ELEMENT local-home (#PCDATA)>

<!ELEMENT local (#PCDATA)>

<!ELEMENT ejb-link (#PCDATA)>

<!ATTLIST auth-constraint id ID #IMPLIED>

<!ATTLIST auth-method id ID #IMPLIED>

<!ATTLIST context-param id ID #IMPLIED>

<!ATTLIST description id ID #IMPLIED>

<!ATTLIST display-name id ID #IMPLIED>

<!ATTLIST distributable id ID #IMPLIED>

<!ATTLIST ejb-link id ID #IMPLIED>

<!ATTLIST ejb-local-ref id ID #IMPLIED>

<!ATTLIST ejb-ref id ID #IMPLIED>

<!ATTLIST ejb-ref-name id ID #IMPLIED>

<!ATTLIST ejb-ref-type id ID #IMPLIED>

<!ATTLIST env-entry id ID #IMPLIED>

<!ATTLIST env-entry-name id ID #IMPLIED>

<!ATTLIST env-entry-type id ID #IMPLIED>

<!ATTLIST env-entry-value id ID #IMPLIED>

<!ATTLIST error-code id ID #IMPLIED>

<!ATTLIST error-page id ID #IMPLIED>

<!ATTLIST mime-mapping id ID #IMPLIED>

<!ATTLIST mime-type id ID #IMPLIED>

<!ATTLIST param-name id ID #IMPLIED>

<!ATTLIST param-value id ID #IMPLIED>

<!ATTLIST realm-name id ID #IMPLIED>

<!ATTLIST remote id ID #IMPLIED>

<!ATTLIST res-auth id ID #IMPLIED>

<!ATTLIST res-ref-name id ID #IMPLIED>

<!ATTLIST res-sharing-scope id ID #IMPLIED>

<!ATTLIST res-type id ID #IMPLIED>

<!ATTLIST resource-env-ref id ID #IMPLIED>

<!ATTLIST resource-env-ref-name id ID

#IMPLIED>

<!ATTLIST resource-env-ref-type id ID

#IMPLIED>

<!ATTLIST resource-ref id ID #IMPLIED>

<!ATTLIST role-link id ID #IMPLIED>

Page 65: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

<!ATTLIST exception-type id ID #IMPLIED>

<!ATTLIST extension id ID #IMPLIED>

<!ATTLIST filter id ID #IMPLIED>

<!ATTLIST filter-class id ID #IMPLIED>

<!ATTLIST filter-mapping id ID #IMPLIED>

<!ATTLIST filter-name id ID #IMPLIED>

<!ATTLIST form-error-page id ID #IMPLIED>

<!ATTLIST form-login-config id ID #IMPLIED>

<!ATTLIST form-login-page id ID #IMPLIED>

<!ATTLIST home id ID #IMPLIED>

<!ATTLIST http-method id ID #IMPLIED>

<!ATTLIST icon id ID #IMPLIED>

<!ATTLIST init-param id ID #IMPLIED>

<!ATTLIST jsp-file id ID #IMPLIED>

<!ATTLIST large-icon id ID #IMPLIED>

<!ATTLIST listener id ID #IMPLIED>

<!ATTLIST listener-class id ID #IMPLIED>

<!ATTLIST load-on-startup id ID #IMPLIED>

<!ATTLIST local id ID #IMPLIED>

<!ATTLIST local-home id ID #IMPLIED>

<!ATTLIST location id ID #IMPLIED>

<!ATTLIST login-config id ID #IMPLIED>

<!ATTLIST role-name id ID #IMPLIED>

<!ATTLIST run-as id ID #IMPLIED>

<!ATTLIST security-constraint id ID #IMPLIED>

<!ATTLIST security-role id ID #IMPLIED>

<!ATTLIST security-role-ref id ID #IMPLIED>

<!ATTLIST servlet id ID #IMPLIED>

<!ATTLIST servlet-class id ID #IMPLIED>

<!ATTLIST servlet-mapping id ID #IMPLIED>

<!ATTLIST servlet-name id ID #IMPLIED>

<!ATTLIST session-config id ID #IMPLIED>

<!ATTLIST session-timeout id ID #IMPLIED>

<!ATTLIST small-icon id ID #IMPLIED>

<!ATTLIST taglib id ID #IMPLIED>

<!ATTLIST taglib-location id ID #IMPLIED>

<!ATTLIST taglib-uri id ID #IMPLIED>

<!ATTLIST transport-guarantee id ID #IMPLIED>

<!ATTLIST url-pattern id ID #IMPLIED>

<!ATTLIST user-data-constraint id ID

#IMPLIED>

<!ATTLIST web-app id ID #IMPLIED>

<!ATTLIST web-resource-collection id ID

#IMPLIED>

<!ATTLIST web-resource-name id ID #IMPLIED>

<!ATTLIST welcome-file id ID #IMPLIED>

<!ATTLIST welcome-file-list id ID #IMPLIED>

DTD : XML 문서의 구조를 명시적으로 정의한 것.

XML문서는 DTD 문서의 정의에 따라 순서에 맞게 기술되어야한다.

<!ELEMENT> : 꺽쇠 안에 가질 수 있는 자식원소(element)와 각각의 자식원소들이 얼마나 많이 존재

할 수 있으며, 그들의 순서가 어떻게 되는지를 정의

? 없거나 하나 존재 (0 ~ 1)

* 없을 수도 있고 여러개 존재할 수도 있다.(0 ~ n)

+ 하나 이상 존재 (1 ~ n)

부호 없음 하나만 존재 (1)

x | y X 이거나 y

<!ATTLIST> : 각 원소가 가질 수 있는 속성(attribute)을 규정

#IMPLIED : element에 attribute가 포함되어 있지 않으면 응용 프로그램이 기본값을 적용하라는 뜻.

<단점> 하나의 문서에 대해서 서로 다른 응용 프로그램들이 각자 다른 기본값을 적용할 수 있다는 것.

Page 66: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

3 Web-app_2_3.dtd 요약 & 예 (web.xml)

<!ELEMENT web-app

(icon?, display -name?, description?, distributable?,

context -param*, <!ELEMENT context-param (param-name, param-value, description?)>

filter*, filter-mapping*,

listener*, <!ELEMENT listener (listener-class)>

servlet*, <!ELEMENT servlet (icon?, servlet -name , display -name?, description?, (servlet-class|jsp-file),

init -param*, <!ELEMENT init -param (param-name, param-value, description?)>

load -on-startup?, run -as?,

security -role-ref*)><!ELEMENT security -role-ref (description?, role -name, role-link?)>

servlet-mapping*, <!ELEMENT servlet -mapping (servlet-name, url-pattern)>

session-config?, <!ELEMENT session -config (session -timeout?)>

mime -mapping*, <!ELEMENT mime -mapping (extension, mime -type)>

welcome -file-list?, <!ELEMENT welcome -file -list (welcome -file+)>

error-page*, <!ELEMENT error-page ((error-code | exception -type), location)>

taglib*, <!ELEMENT taglib (taglib-uri, taglib-location)>

resource -env -ref*, resource-ref*,

security -constraint*, <!ELEMENT security -constraint (display -name?,

web-resource-collection+, <!ELEMENT web-resource -collection

(web-resource -name , description?, url-pattern*, http-method*)>

auth-constraint?, <!ELEMENT auth-constraint (description?, role-name*)>

user-data -constraint?)> <!ELEMENT user-data -constraint (description?,

transport -guarantee)> NONE, INTEGRAL, or CONFIDENTIAL.

login-config?, <!ELEMENT login-config

(auth -method?, "BASIC", "DIGEST", "FORM", or "CLIENT -CERT"

realm-name?, Only for BASIC

form-login-config?)><!ELEMENT form-login-config (form-login-page, form-error-page)>

security -role*, <!ELEMENT security -role (description?, role -name)>

env -entry*, ejb-ref*, ejb-local-ref*)>

Page 67: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

Example 1) Simple Application

<web-app>

<display-name>A Simple Application</display-name>

<context-param>

<param-name>Webmaster</param-name>

<param-value>[email protected]</param-value>

</context-param>

<servlet>

<servlet-name>catalog</servlet-name>

<servlet-class>com.mycorp.CatalogServlet</servlet-class>

<init-param>

<param-name>catalog</param-name>

<param-value>Spring</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>catalog</servlet-name>

<url-pattern>/catalog/*</url-pattern>

</servlet-mapping>

<session-config><session-timeout>30</session-timeout></session-config>

<mime-mapping>

<extension>pdf</extension>

<mime-type>application/pdf</mime-type>

</mime-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

</welcome-file-list>

<error-page>

<error-code>404</error-code>

<location>/404.html</location>

</error-page>

</web-app>

Page 68: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

Example 2) Secure Application

<web-app>

<display-name>A Secure Application</display-name>

<servlet>

<servlet-name>catalog</servlet-name>

<servlet-class>com.mycorp.CatalogServlet</servlet-class>

<init-param>

<param-name>catalog</param-name>

<param-value>Spring</param-value>

</init-param>

<security-role-ref>

<role-name>MGR</role-name> <!-- role name used in code -->

<role-link>manager</role-link> <!-- role name in security-role-->

</security-role-ref>

</servlet>

<servlet-mapping>

<servlet-name>catalog</servlet-name>

<url-pattern>/catalog/*</url-pattern>

</servlet-mapping>

<security-constraint>

<web-resource-collection>

<web-resource-name>SalesInfo</web-resource-name>

<url-pattern>/salesinfo/*</url-pattern>

<http-method>GET</http-method>

<http-method>POST</http-method>

</web-resource-collection>

<auth-constraint><role-name>manager</role -name></auth-constraint>

<user-data-constraint>

<transport-guarantee>CONFIDENTIAL</transport-guarantee>

</user-data-constraint>

</security-constraint>

<security-role><role-name>manager</role -name></security-role>

</web-app>

Page 69: › attachment › hk10.pdf 1. Primary Source (허가받은 적 없음…) ? Ken Zrobok : Sun Certified Web Component Developer Study Guide.pdf

4 web-jsptaglibrary_1_2_dtd 요약. (tld file)

<!ELEMENT taglib

(tlib-version, jsp-version, short-name, uri?, display -name?, small -icon?, large-icon?, description?,

validator?, <!ELEMENT validator (validator-class,

init-param*, <!ELEMENT init-param (param-name, param-value, description?)>

description?) >

listener*, <!ELEMENT listener (listener-class) >

tag+ <!ELEMENT tag (name , tag-class, tei-class?, // fully qualified Java class name

body -content?, // tagdependent | JSP(default) | empty

display -name?, small-icon?, large -icon?, description?,

variable*, <!ELEMENT variable ( (name -given | name -from-attribute), variable -class?, declare?,

scope?, // NESTED(default) | AT_BEGIN | AT_END

description?) >

attribute*, <!ELEMENT attribute (name,

required?, // true | false(default) | yes | no

rtexprvalue?, // true | false(default) | yes | no

type?, // String

description?) >

example?) >

)>