. 1. Primary Source (허가받은 적 없음…) ✍ Ken Zrobok : Sun
Certified Web Component Developer Study Guide.pdf. ✍ Michelle ...
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]
< 목 차 > 제 1 장. Servlets. _______________________________________________________________ 5 1
2
3
4
5
6
7
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
Servlet Container Model.______________________________________________________11 2.1
Servlet Context Init Parameter : _______________________________________ 11
2.2
Listener : _______________________________________________________________ 11
2.3
Distributable Application. ___________________________________________________________ 12
Structure & Deployment._____________________________________________________ 13 3.1
Application Structure ______________________________________________________________ 13
3.2
, ________________________________________________________ 13
Session Management. _______________________________________________________ 15 4.1
Session __________________________________________________________________________ 15
4.2
Session Invalidating : _________________________________________________ 15
4.3
Session Tracking.__________________________________________________________________ 15
Server-Side Exception. ______________________________________________________ 17 5.1
Error Page. ______________________________________________________________________ 17
5.2
_____________________________________________________________________ 17
5.3
sendError, setStatus _______________________________________________________________ 18
5.4
log. _____________________________________________________________________________ 18
Security. _________________________________________________________________ 19 6.1
보안 용어._______________________________________________________________________ 19
6.2
, , _________________________________ 19
6.3
Authentication Type : BASIC, DIGEST, CLIENT-CERT, FORM ___________________________ 21
6.4
____________________________________________________________________ 23
Thread-safe Servlets.________________________________________________________ 24
제 2 장. JSPs._________________________________________________________________ 26 8
The JSP Model ____________________________________________________________ 26
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
____________________________________________________________________ 31
10.2
, _________________________________________________ 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) - , , , _______________ 35
11.3
Step 3 : DD (web.xml) - ______________________________________________________ 36
11.4
Step 4 : taglib Directive (jsp page) - ____________________________________ 36
11.5
Step 5 : Using Custom Tag (jsp page) - __________________________________ 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
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
제 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 reques ts들을
핸들러 메소드들로 디스패칭하기 때
문.
1.2 Http Method 특징. 1.2.1 : 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()
? 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() comm its response.
1.5 Redirect ? void HttpServletResponse.sendRedirect(String url) throws IllegalStateException, IOException 1. redirect page를 만들기 전에, status 를 SC_MOVED_TEMPORARILY로 s e t하고, location header를 set, response buffer에 대한 implicit reset을 수행. 2. 상대경로 가능. => containe r가 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()
? 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
? 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
? 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들을 s e t할 수 없음. => 무시됨. ? 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 가 깨질 수 있으므로 삼가는게
좋음. 대신 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);
2
Servlet Container Model. 2.1 Servlet Context Init Parameter : 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 ? ? : application.에서 unique. ?
2.2 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 ServletCo ntextAttributeListener ? 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는
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 ? : 하나씩 밖에 설정 못함. “+|*” 가 없음. ? 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들로 전달할 필요 없음.
3
Structure & Deployment. 3.1 Application Structure 3.1.1 Co ntext Path ? application content들의 URL namespace를 결정. ? 같은 이름의 context path는 container에 의해 거부되어야 함. ? case-sensitive. 3.1.2 WEB-INF ? Application의 docume nt 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 , 3.2.1 ? 1. JSP 파일이 specified되고, load -on-startup element가 존재하면, JSP 파일은 precompile되고 load 되어야 함. ? 1. dd 내에서 쓰이는 logical name. canonical name. application에서 unique. ? : Fully qualified class name. ? 3.2.2 ? 1. logical servlet name과 url pattern 사이의 mapping을 정의. 2. mapping순서
1) explicit mapping : /index.html 2) prefix mapping : /kyo/* 3) extension mapping : *.jsp 4) default mapping : “ /” . application에 대한 default sertvlet을 indentify. ? 3.2.3 예. catalog com.mycorp.CatalogServlet catalog Spring catalog /catalog/*
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 : 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 ? ? 1. minutes로 정의. (Tomcat default : 30). 2. Timeout이 0보다 작거나 같으면, session은 expire되지 않음. 30
4.3 Session Tracking. 4.3.1 HTTP Cookie : isRequestedSessionIdFromCookie ? Session tracking에 가장 많이 사용되고, 모든 container는 이를 지원해야 함. ? Container가 client로 cookie를 보내면, client는
계속되는
return. (명확히 request를 session에 관련시킴). ? Session tracking cookie의 name 은 JSESSIONID여야 함.
request마다 cookie를
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일 수 있음.
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들을 s ervice 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을 extra ct함. 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 5.2.1 ? : unique ? : fully qualified class name. unique. ? 1. location은 ‘ /’ 로 시작해야 함. 2. dynamic page 가능 : javax.servlet.error.status_code, exception_type, message 5.2.2 예 404 /404.html
java.lang.NumberFormatException /MyException.html
5.3 sendError, setStatus 5.3.1 void
HttpServletResponse.sendError(int
s tatusCode
[,
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_MOVED_PERMANENTLY,
SC_NO_CONTENT,
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를 씀.
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 , , 6.2.1 ? 1. role -name “ *” 은 특별한 의미를 가지므로, 쓸 수 없음. ? 1. security role reference를 정의된 secrity role에 link시킴. 2. security-role element들에서 정의된 security role들중 하나의 과 같 아야 함. 6.2.2 ? 6.2.3 ? ? 1. HTTP method (GET | POST | …)를 가짐. 2. 아무 HTTP method도 specified되지 않으면, security constraint는 모든 HTTP method들에 적용됨. 6.2.4 ? 1. resource들에 접근하기 위해 user들이 속해야 하는 security roles. 2. 아무 role 도 정의되지 않으면, 어느 user도 이 부분에 접근이 허용되지 않음. ? 1. role -name은 의 role -name과 일치하거나, 모든 role들을 나타내 는 reserved된 “ *” 이어야 함. 2. “ *” 과 role name들이 모두 나타나면, container는 모든 role들로 해석함. 3. role name들은 case-sensitive임.
6.2.5 ? ? 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 ? ? 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은 is UserInRole (“ FOO” )을 하고, 결과는 true가 됨. A Secure Application … FOO manager … SalesInfo /salesinfo/* GET POST
API call인
manager CONFIDENTIAL manager
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.
? 현재 많이 사용되지 않으므로, 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를 사용하여 가 반환되고, 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” 의 이름을 가져야 함.
6.3.4 CLIENT-CERT Authentication ? Public Key Certificate(PKC) 사용 ? Authenticate server and optionally the client ? 많은 browser들은 certificate를 보내기 전에 user에게 pwd를 요구. ? Browser가 certificate를 갖지 않거나, authorized되지 않았다면, 거부됨.
? 단점 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 ? ? : Basic authentication이 아니면, 무시됨. ? 1. application에 사용될 authentication mechanism을 정의. 2. 보호되는
resource들에
접근하려면,
authentication
mechanism을
authenticated되어야 함. 3. “ BASIC” , “DIGEST” , “ FORM” , “ CLIENT-CERT” 의 값을 가져야 함. ? 1. form based authentication이 아니면, 무시됨. ? : “ /” 로 시작. ? : “ /” 로 시작. 6.4.2 예. BASIC/DIGEST/FORM/CLIENT-CERT HTTP Realm Name /loginpage.html /errorpage.html
사용하여
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에 대해서, containe r는 servlet 선언마다 하나의 instance만 사용해야 함. ? SingleThreadModel
interface를
implements 하는
servlet에
대해서,
container는
heavy request load 를 처리하고 특별한 instance에 대한 request들을 serialize하기 위해, multiple instance들을 instantiate할 수 있음. ? Servlet이 deployment descriptor에서 “ distributable”로 mark 된 application의 일부로 deployed된 경우에, container는 V M마다 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 하지 않은 s ervlet들에 대해서, service method(또는 HttpServlet abstract class의 service method로 dispatched된 doGet, doPost같은 method들)가 synchronized로 정의되어 있으면, container는 instance pool을 사용한 접근을 할 수 없고, request들을 serializing해야 함. ? 성능상 나쁜 영향 때문에 service method를 synchronizing시키지 말 것이 권장됨.
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에 대해 책임을 갖고, 명시적으로 이 경우를 처리해야 함.
제 2 장. JSPs. 8
The JSP Model 8.1 JSP Tag Syntax ? Directive : ? Declaration : ? Scriptlet : ? Expression : : 뒤에 ‘ ;’ 이 없음.
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 : 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.
? extends =” …” 1. no default. Fully qualified class name. 2. class는 JspPage 또는 HttpJspPage interface를 implement해야 함.
8.4 Equivalent XML-based Tag. 8.4.1 Directive : == 8.4.2 Declaration : … 8.4.3 Scriptlet : … 8.4.4 Expression : … 8.4.5 예외. ? ==
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 compone nt임. 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 clas s의 세세한 점에서 유동성을 가짐으로써, 가장 부각되는 performance issue 인 QOS(quality-o f-service)를 address하기 위해 이를 이용할 수 있음. 8.5.3 Request phase ? container는
request들과 event들에
대한
response에
이 class의
하나
이상의
instance들을 다룸. ? Container는 request와 response object들을 instantiating해야 하고, 적절한 JSP page
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 JspWriter
Purpose JSP의 output stream에 write할 JspWriter.
Scope page
PrintWriter와 BufferedWriter의 기능들을 갖고 있으나,
out
PrintWriter와 달리 IOException을 throw함. flush, int getBufferSize()
response
HttpServletResponse
Sub of ServletResponse
page
request
HttpServletRequest
Sub of ServletRequest
request
page
implementation class
Equivalent servlet instance “this ”
page
HttpSession
Http protocol에 대해서만 valid.
session
session
request.getSession(). ServletContext
application
GenericServlet.getServletContext().
applicati
servlet engine의 resource들에의 access 를 제공
on
(resources, attributes, init cotext parameters, request dispatcher, server info, URL & MIME resources ). PageContext
Environment for this page.
page
이 page와 관련된 모든 scope들에의 접근을 제공. Container가 error page들과 include/forward page들의
pageContext
parameter등을 처리. page에 사용된 object들에 대한 reference들, impleme ntation-dependent features 들을 저장할 context.
e xception
Throwable
error page 호출로 가는 uncaught Throwable.
page
config
ServletConfig
Servlet instance에 specific 함 Generic Servlet.getServletConfig().
8.7 Sciptlet Syntax. 8.7.1 Conditional statement 8.7.2 Iteration statement
page
9
Reusable Web Component. 9.1 include Directive ? ? Included되는 file 은 container가 접근 가능해야함. ? translation time에 정의된 resource의 text 를 parsing 을 하고, include함. ? include되는 file 도 처리될 element들을 가질 수 있음. ? resource를 static object로 간주하여 JSP page안에 있는 byte 들이 include됨.
9.2 include Action ? ? {}* ? 현 page와 같은 context내의 static 과 dynamic 한 resource들의 inclusion을 제공함. ? 내용은 parsing되지 않은 상태로 including됨. ? resource를 dynam ic object로 간주하여, 그 object로 request가 보내져서 처리 결과가 include됨. ? 예 :
10 JavaBeans 10.1 10.1.1 Syntax ? 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
? body 1. action에 표시된 Bean 이 생성될 때만, body부분이 호출됨 : one -time initialization. 2. body는
새로
생성된
object를
modify하는데
쓰이는
scriptlet들이나
jsp:setProperty tag들을 포함하지만, body의 내용에는 제한이 없음. 10.1.3 예 ? ? com.myco.myapp.Connecion type의 “ connection” 이라는 name 을 가진 Bean이 이미 생성되어 있는 것을 찾거나 지금 새로 생성됨으로써
이후의 actio n들에서 사용 가능.
10.2 , 10.2.1 ? Syntax. 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. : 모든 request parameter들이 matching되는 “user”bean의 property들로 set. 2. : request parameter “ username”이 “user”bean의 “name ”property로 set. 3. : request parameter “name”이 “user”bean의 “name ”property로 set. 4. 10.2.2 ? ==
10.3 JSP & Servlet Scope Bean Scope
Servlet Scope
request
HttpServletRequest
session
HttpSession HttpServletRequest.getSession()
applic ation
ServletContext GenericServlet.getServletContext() GenericServlet.getServletConfig().getServletContext()
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. No n-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)
사용하여
회복되며,
그리고나서
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 EVAL_BODY_INCLUDE
All
EVAL_BODY_BUFFEDRED
BodyTag only
EVAL_BODY_AGAIN SKIP_BODY
doAfterBody
doEndTag
Iteration All
EVAL_BODY_TAG
All 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.
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) - , , , 11.2.1 ? 11.2.2 ? ? 1. javax.servlet.jsp.tagext.Tag interface를 implement하는 tag handler class. 2. Fully qualified Java class name. ? 1. javax.servlet.jsp.tagext.TagExtraInfo의 subclass. 2. Fully qulified Java class name. ? 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는 비어있어야 함. ? 1. : canonical name. 2. 1) nesting attribute의 필수/선택을 정의. 2) Value는 true | false | yes | no. default는 “false” . 3. 1) nesting attribute가 value로 s criptlet expression들을 가질 수 있는지 정의함. 2) Attribute value가 request time에 dynamically 계산될 수 있게 됨. 3) Value는 true | false | yes | no. default는 “false” , 즉 static. 4.
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. 예. username true false java.lang.String
11.3 Step 3 : DD (web.xml) - 11.3.1 ? ? URI들과 TLD resource path들 사이의 mapping. ? : absolute or relative. 11.3.2 예. /myPRlibrary /WEB -INF/tlds/PRlibrary_1_4.tld
11.4 Step 4 : taglib Directive (jsp page) - ? jsp page가 tag library를 사용함을 선언. ? uri 1. tag library를 uniquely identify. Relative 가능. 2. uri는 web.xml에서 정의될 수도 있고, 직접 tld 파일을 지정할 수도 있음. ? action들의 사용을 구별하는 tag prefix를 library에 연관시킴. ? 예 :
11.5 Step 5 : Using Custom Tag (jsp page) - ? or : empty custom tag ? : custom tag with attributes ? some JSP code as the body : surrounding JSP code ? some condition : nested custom tags
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때문에 복잡성 증가.
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.
제 3 장. Design Pattern 상세. 1
Value Objects 1.1 Context 1.1.1 Applic ation 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-g rained service method들을 제공. 그 service method들 중의 어떤 것은 method들을 호출한 client 에 게 data 를 return. 그런 경우에는 client는 모든 attribute value 들에 대한 값을 얻을 때 까지 여러 번 session bean의 get method들을 호출해야 함. ? Entity bean : 지속적인 business component들을 구현. Entity bean은 각 attribute 에 대해 a c c essor 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 처리의 빈도가 많음.
? 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를 필요로 할 수 있다.
? single type의 client를 지원하기 위한 application을 개발할 때는, presentation과 control을 위해서 data access logic 을 interface -specific logic 과 뒤섞는 것이 좋을 수 있음. 하지만, 그런 접근은 각 type의 client interface를 지원하도록 다른 application들 을 개발할 필요가 있는 multiple type의 client들을 지원할 필요가 있는 enterprise system들에 적용하기에는 부적합함. ? No n-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하고 유지하기 쉽게 함.
? 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를 변화시키는 것을 포함함. ? Us e r interaction들과 model action들의 결과에 기반하여, controller는 적절한 view의 선택으로 응답함.
2.6 MVC architecture의 장점. 2.6.1 Mutiple view들이 같은 model을 사용. ? model과 view의 분리는 같은 enterprise model을 사용하는 multiple view들을 허용함.
? 결과적으로 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들은 다른 syste m에 있는 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 systembased 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들 그리고
심지어 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에 따라 변함. 이 A P I들과 그들의 능력들 또한 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
으로 너무 많은 호출들을 하기 때문에, 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 c o d e 의 세세한 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을 줄이는 데 사용될 수 있음.
제 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,
Called by the servlet container to allow the servlet to respond to a request.
ServletResponse) 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
Returns
the names of the servlet's initialization parameters as an
getInitParameterNames()
Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
ServletContext
Returns a reference to the ServletContext in which the caller is executing.
getServletContext() 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
Returns the
names of the context's initialization parameters as an
getInitParameterNames()
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.
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 Returns a ServletContext object that corresponds to a specified URL on the
uripath)
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
Returns the resource located at the named path as an InputStream object.
getResourceAsStream(String path) RequestDispatcher
Returns a RequestDispatcher object that acts as a wrapper for the resource
getRequestDispatcher(String path)
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
Returns a RequestDispatcher object that acts as a wrapper for the named
getNamedDispatcher(String name)
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.
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
Retrieves
the
body
of
the
request
as
binary
data
using
a
getInputStream()
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
Returns a RequestDispatcher object that acts as a wrapper for the
getRequestDispatcher(String path)
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.
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
Returns a ServletOutputStream suitable for writing binary data in the
getOutputStream()
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 chars et= 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.
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 Serializable init()
GenericServlet
implements
Servlet,
ServletConfig,
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,
Dispatches client requests to the protected service method. There's no
ServletResponse)
need to override this method.
protected
Receives standard HTTP requests from the public service method and
service(HttpServletRequest,
dispatches them to the doXXX methods defined in this class.
HttpServletResponse)
There's no need to override this method.
doGet(HttpServletRequest,
Should be safe and idempotent (repeatable)
HttpServletResponse)
Override to service GET requests. HEAD requests are also satisfied since doHead internally uses this method with a specialized response.
doPost(HttpServletRequest,
Need not be safe or idempotent.
HttpServletResponse)
Override to service POST requests.
doPut(),
doDelete (),
doHead (),
These methods are not common and service the corresponding requests.
doTrace(), doOptions () long getLastModified ()
Returns the time the HttpServletRequest object was last modified
1.8 HttpServletRequest Interface
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 d i d n o t include a n y 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
Returns the current HttpSession associated with this request or, if if there
create])
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.
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
Checks whether the requested session ID is still valid.
isRequestedSessionIdValid () boolean
Checks whether the requested session ID came in as a cookie.
isRequestedSessionIdFromCookie () boolean
Checks whether the requested session ID came in as part of the request
isRequestedSessionIdFromURL()
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
value / date value respectively. These methods allow response headers to name,
int
addDateHeader(String name,
long
value)
value)
Add a response header with the given name and String value / integer
have multiple values.
setHeader(String
name,
String
Set a response header with the given name and String value / integer
value)
value / date value respectively. If the header had already been set, the
setIntHeader(String name, int value)
new value overwrites the previous one. The containsHeader method can
setDateHeader(String
be used to test for the presence of a header before setting its value.
name,
long
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 errorpage 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.
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
HttpSessionBindingListener,
if
the
the
new
object
container
implements 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
HttpSessionBindingListener,
if
the the
object container
implements 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.
1.11 RequestDispatcher Interface forward (ServletRequest,
Forwards a request from a servlet to another resource (servlet, JSP file,
ServletResponse)
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,
Includes the content of a resource (servlet, JSP page, HTML file) in the
ServletResponse)
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
Implementations of this inte rface receive notifications about changes to
ent)
the servlet context of the web application they are part of. To receive
contextDestroyed(ServletContextEv
notification events, the implementation class must be configured in the
ent)
deployment descriptor for the web application.
1.14 ServletContextAttributeListener Interface attributeAdded(ServletContextAttrib
Implementations of this interface receive notifications of changes to the
uteEvent)
attribute list on the servlet context of a web application. To receive
attributeRemoved(ServletContextAtt
notification events, the implementation class must be configured in the
ributeEvent)
deployment descriptor for the web application.
attributeReplaced(ServletContextAtt ributeEvent)
1.15 HttpSessionListener Interface sessionCreated(HttpSessionEvent)
Implementations of this interface are notified of changes to the list of
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
Objects that are bound to a session may listen to container events
nt)
notifying them that sessions will be passivated and that sess ion will be
sessionWillPassivate(HttpSessionEv
activated. A container that migrates session between VMs or persists
ent)
sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.
1.17 HttpSessionAttributeListener Interface attributeAdded(HttpSessionBindingE
This listener interface can be implemented in order to get notifications of
vent)
changes made to sessions within this web application.
attributeRemoved(HttpSessionBindi ngEvent) attributeReplaced(HttpSessionBindin gEvent)
1.18 HttpSessionBindingListener Interface valueBound(HttpSessionBindingEve
Causes an object to be notified when it is bound to or unbound from a
nt)
session. The object is notified by an HttpSessionBindingEvent object. This
valueUnbound(HttpSessionBindingE
may be as a result of a servlet programmer explicitly unbinding an
vent)
attribute from a session, due to a session being invalidated, or die to a session timing out.
2
web -app_2_3.dtd 분석.
- SCCD 1기 손수정 ※ 원본 DTD를 참고해서 같이 보시기 바랍니다.
1. GUI도구에서 부모요소를 나타내기 위한 icon에 대한 참조 → 16X16 pixel icon의 위치 기술(gif, jpeg) → 32X32 pixel icon의 위치 기술 2. : 부모요소의 짧은 이름 기술. GUI도구에서 표현 3. : 부모요소의 설명 기술 4. 선언시, 분산된 서블릿 컨테이너에 웹 애플리케이션이 배치될 수 있음을 의미 5. 설명 DTD
context 초기화 매개변수를 선언
예
thisIsMyFirstparam 3 → Boolean, Double, Float, Integer, String 가능
6. : 필터 선언 DTD
예
Games Filter filters.StopGamesFilter starthour 10
7. : 필터를 서블릿이나 URL 세트에 mapping DTD
or
예
Games Filter FindProd
8. 설명 DTD
애플리케이션의 listener 등록
예
CounterListenerExample
9. 설명 DTD
서블릿을 선언
or → 애플리케이션이 시작될 때, 서블릿이 로딩되도록 설정 예
Time2 TimeServlet2 → class 명 thisIsMyFirstparam 1 1 → 낮은 값일수록 먼저 loading된다. → 서블릿의 보안 역할 이름 설정 < r o l e -name>abc < r o l e -link>admin
10. 설명 DTD
서블릿과 URL 패턴을 mapping
예
Time2
/Time → http://localhost:8080/Time 으로 접근가능
11. 설명 DTD
웹 애플리케이션의 세션 트레킹을 설정 → 분단위로 설정
예
45
12. 설명 DTD
파일 이름의 확장자와 MIME 타입의 연결 설정
예
< e xtension>wml → wml 파일을 다음과 같은 MIME type으로 전송 text/vnd.wap.wml
13. 설명
브라우저가 웹페이지나 서블릿이 아닌 디렉토리를 요구했을 때, 컨데이너가 브라우저에게 넘겨주기 위해 찾아야할 파일의 목록설정.
DTD
예
index.html
14. 설명
에러 코드나 예외 타입과 웹 애플리케이션의 자원의 위치를 mapping
DTD
or
예
400 /400.html
15. 설명
JSP 태그 라이브러리를 설정
DTD
→ 태그 라이브러리를 인식하기 위한 URI
→ 태그 라이브러리 기술자 파일(.tld 파일) 예
/struts.tld /WEB -INF/struts.tld
16. 설명 DTD
웹 애플리케이션이 관리 객체를 참조한다는 것을 선언 < ! E L E M ENT resource-env-ref-name (#PCDATA)>
예
jms/StockQueue javax.jms.Queue
17. 설명
EJB 컴포넌트나 JDBC DataSource 객체 같은 외부 자원에 대한 웹 애플리케이션의 레퍼런스를 정의
DTD
예
Primary database jdbc/primaryDB javax.sql.DataSource → 자바 클레스 타입 CONTAINER → CONTAINER or SERVLET < r e s -sharing -scope>Shareable →Shareable or Unshareable
18. 설명 DTD
보안제약과 resource collection을 연결시키는데 사용
예
< w e b -resource-name>SecretProtection < u r l -pattern>/SalaryServer < u r l -pattern>/Server < h t t p -method>GET < h t t p -method>POST < r o l e -name>manager CONFIDENTIAL → NONE, INTEGRAL, CONFIDENTIAL
19. 설명
인증 메소드를 설정하거나 애플리케이션에서 이용되는 영역(realm) 이름 혹은 폼 기반 로그인에 대한 속성 값을 설정
DTD
예
FORM → BASIC, DIGEST, FORM, CLIENT-CERT Default → http 기본인증에 쓰이는 영역의 이름 설정 → 폼 기반 로그인에서 로그인페이지와 에러페이지를 설정 < f o r m -login-page>/login.html < f o r m -error-page>/error.html
20. 설명 DTD
보안 역할을 정의하고 이것은 웹 애플리케이션에 보안제약을 적용한다.
예
manager
21. 설명 DTD
java:comp/env 컨텍스트 안의 JNDI 검색을 통한 애플리케이션의 환경 항목을 정의
예
Send pincode by mail mailPincode → 환경항목의 검색이름 설정 false → 애플리케이션에 기본 설정된 환경항목 값 java.lang.Boolean →java.lang.Integer, java.lang.double, java.lang.Float, or java.lang.String
22. 설명 DTD
엔터프라이즈 빈즈의 레퍼런스를 정의
예
Cruise ship cabin ejb/CabinHome →서블릿 코드가 EJB 레퍼런스를 얻는데 사용하는 JNDI의 이름 Entity → 빈의 타입 : Entity or Session com.titan.cabin.Cabinhome →EJB의 홈 인터페이스의 패키지 명을 포함한 이름 com.titan.cabin.Cabin →EJB의 원격 인터페이스의 패키지를 포함한 이름
23. 설명 DTD
지역 엔터프라이즈 빈즈의 레퍼런스를 정의
#IMPLIED>
#IMPLIED>
#IMPLIED>
#IMPLIED>
DTD :
XML 문서의 구조를 명시적으로 정의한 것. XML문서는 DTD 문서의 정의에 따라 순서에 맞게 기술되어야한다.
: 꺽쇠 안에 가질 수 있는 자식원소(element)와 각각의 자식원소들이 얼마나 많이 존재 할 수 있으며, 그들의 순서가 어떻게 되는지를 정의 ?
없거나 하나 존재 (0 ~ 1)
*
없을 수도 있고 여러개 존재할 수도 있다.(0 ~ n)
+
하나 이상 존재 (1 ~ n)
부호 없음
하나만 존재 (1)
x|y
X 이거나 y
: 각 원소가 가질 수 있는 속성(attribute)을 규정 #IMPLIED : element에 attribute가 포함되어 있지 않으면 응용 프로그램이 기본값을 적용하라는 뜻. 하나의 문서에 대해서 서로 다른 응용 프로그램들이 각자 다른 기본값을 적용할 수 있다는 것.
3
Web-app_2_3.dtd 요약 & 예 (web.xml)
filter*, filter -mapping*, listener*, servlet*,
load -on -startup?, run -as?, security -role -ref*)>< !ELEMENT security -role -ref (description?, role -name , role -link?)>
servlet -mapping*, session -config?, mime -mapping*, welcome -file -list?, error -page*, taglib*, resource -env -ref*, resource -ref*, security -constraint*,
auth -constraint?, user -data -constraint?)> NONE, INTEGRAL, or CONFIDENTIAL.
login -config?,
Only for BASIC
form-login -config?)> security -role*, env -entry*, ejb -ref*, ejb -local -ref*)>
Example 1) Simple Application
A Simple Application Webmaster
[email protected] catalog com.mycorp.CatalogServlet catalog Spring catalog /catalog/* 30 pdf application/pdf index.jsp index.html index.htm 404 /404.html
Example 2) Secure Application
A Secure Application catalog com.mycorp.CatalogServlet catalog Spring MGR manager catalog /catalog/* SalesInfo /salesinfo/* GET POST manager CONFIDENTIAL manager
4
web -jsptaglibrary_1_2_dtd 요약. (tld file)
description?) > listener*, tag+
// fully qualified Java class name
// tagdependent | JSP (default) | empty
display -name?, small -icon?, large -icon?, description?, variable*,
// NESTED(default) | AT_BEGIN | AT_END
description?) > attribute*,
// true | false(default) | yes | no
rtexprvalue?,
// true | false(default) | yes | no
type?,
// String
description?) > example?) > )>