목차
?개발 방법론 비교
?EL; Expression Language
?JSTL; JSP Standard Tag Libraries
?JSF; JavaServer Faces
?Simple Tag Handler
?Tag Files
?환경설정 파일 web.xml 의 jsp 지원강화
?참고자료
개발방법론
?Model 1 - 페이지 중심
?Model 2 - 모델,뷰,컨트롤러 MVC?Model 2X – Model 2+XML
?기타 개발 방법 – 다른 언어 스타일
방법론 비교 #1
표준잡기 힘듦
소스 가독성 떨어짐패턴 변경 시 모두 재작성
기존 코딩과 차이 많이 남매번 거의 재시작
초기 빠름갈수록 느려짐
Model 1
표준화된 코드공동작업
모듈별 고찰 쉬움한꺼번에유지보수
기존 표준에 맞게 개발확장성이 용이한 편추가개발
초기 느림재사용성으로 빨라짐속도
Model 2구분
방법론 비교 #2
처음 컴파일 타임
필요없음
테스트/데모 페이지
작을수록 유리
Model 1
이미 컴파일된 코드속도
클래스 바뀔 때마다JVM refresh 필요재시동
기존 표준에 맞게 개발확장성이 용이한 편적용점
많을수록 유리인원
Model 2
에러 줄이는 법
?정확한 구현목표? UML / 스토리보드 등
?가능하면 툴을 사용한다.?문법오류 감소 , 리팩토링의 용이
?Util class 사용
?Copy & Paste?에러메시지 잡기? try {} catch(Exception e) {
System.out.println(e.toString()); }
문서화/주석
?유지보수를 위한 포석
?javadoc 이용?먼저 주석문 작성 후 채워 나가기
?사용 예를 기입
공동작업 요령
?항상 최신의 버전을 유지할 것
?FTP 사용시?먼저 다운로드받고, 갱신하고, 업로드
?CVS (concurrent versions system) 이용?버전 충돌시 diff 등을 통해서 정리 가능
JSP 작업시 유의사항
?유닛 테스트로 작업코드 세분화 테스트
?리로딩에 관한 세가지 방법.?1. 서블릿의 경우 Context 에
reloadable="true" 를 지정함으로 리로딩 가능.
conf/ 에 있는 server.xml 에서 아래부분을 수정.기본은 주석처리된 상태
<!-- Tomcat Root Context -->
<!--
<Context path="" docBase="ROOT" debug="0"/>-->
를 아래처럼 변경
<!-- Tomcat Root Context --><Context path="" docBase="ROOT" debug="0" reloadable="true" />
JSP 작업시 유의사항
? 2. manager 를 이용?웹 어플리케이션 관리자
?Ant 와 manager 의 연결 사용
?ant install/reload/remove
? 3. 그래도 안되는 경우? ClassCastException 등의 에러가 날 경우에는 톰
캣을 재시동
JSP 작업시 유의사항
?세션의 보존?재시동/리로딩시에 기존의 세션은 보존된다.
since 4.1
?web.xml 파일의 변경사항 반영?4.0 이전 재시동/ 4.1 manager 로 반영/
5.0 변경즉시
Expression Language;EL JSTL의 기본
?The EL is a language for accessing runtime data from various sources.
?쉬운 문법 체계.?객체의 접근이 쉽고 직관적으로 표시
?스크립팅 요소의 감소를 위해 도입
Expression Language;EL implicit objects 내장 객체
? pageContext - PageContext 객체
? pageScope - page-scoped 속성 이름과 값들의 Map? requestScope - request-scoped 속성 이름과 값들의 Map
? sessionScope - session-scoped 속성 이름과 값들의 Map
? applicationScope - application-scoped 속성 이름과 값들의 Map? param - 파라메터 이름과 하나의 값
? paramValues - 파라메터 이름과 String[] 형태의 값
? header - 헤더 이름과 하나의 값? headerValues - 헤더 이름과 String[] 형태의 값
? initParam - context 초기 파라메터 이름과 String 값
? cookie - 쿠키 이름과 하나의 쿠키객체에 있는 값
Expression Language;EL JSP2.0 EL
?Functions?JSTL EL 의 확장 JSP2.0 EL의 기능
?TagLib 에서 선언된 함수를 정적메소드로사용가능
JSP Standard Tag Libraries; JSTL 개요
?http://jakarta.apache.org/taglibs 의표준 커스텀태그들을 채용
?JSTL 은 EL을 지원하기 위해 시작됨?표준 커스텀태그들을 모아서 배포?http://java.sun.com/products/jsp/jstl
?http://jakarta.apache.org/taglibs
JSP Standard Tag Libraries; JSTL 개요
?JSTL 처리영역?주로 프리젠테이션 단계에서 효과적으로 사용됨
?4가지 scope의 Attribute 에 있는 객체 접근 가능
?조건, 반복, 이동에 관한 태그지원
?internationalization 과 포맷에 관한 지원?DataSource 를 이용한 jdbc 관련 지원
?XML 파싱과 생성에 관한 지원
JSTL 설치
? 설치될 환경? j2sdk1.2 이상 설치
? 다운로드/설치? quick install
http://java.sun.com/webservices/webservicespack.html?java web service developer pack 을 받아 설치하면
tomcat4와 jstl 자동 설치
? Add-on install http://jakarta.apache.org/taglibs , Release 1.0.1 http://jakarta.apache.org/builds/jakarta-taglibs/releases/standard/nightly build – 모든 taglibs taghttp://cvs.apache.org/builds/jakarta-taglibs/nightly/
JSTL 설치
?JSTL 예제 설치?Nightly build의 jakarta-taglibs-20030128.zip 파일 압
축을 풀고 jakarta-taglibs/standard 디렉토리에 접근
?standard-examples.war 파일을 jstl.war 로 바꾼 후webapps 에 복사하고 Tomcat 을 재기동. ?http://localhost:8080/jstl/ 로 예제를 실행
?ROOT 설치?jstl.war 압축 해제된 곳의 WEB-INF/lib/*.jar 파일들과
WEB-INF/*.tld 디렉토리를 통째로 ROOT Context의WEB-INF/lib 와 WEB-INF/ 에 복사하고,
?jstl 예제의 WEB-INF/ 에 있는 web.xml 파일의<web-app> 태그 안에 있는 <taglib> 8개를 복사해서?ROOT/WEB-INF/web.xml 파일의 <web-app> 태그에
복사후 Tomcat 재기동.
JSTL 기본 사용법
?Parameter? http://localhost:8080/test/jstl/para.jsp?id=okjsp
?<c:out value="${param.id}"/>
?Attribute of 4 scopes(application, session, request, page)?session 객체 생성
<h1>session put, get</h1><c:set var="sess" value="session touched" scope="session"/>
sess: <%=session.getAttribute("sess")%><h1>session remove</h1><c:remove var="sess" scope="session"/>
sess: <%=session.getAttribute("sess")%>
JSTL CORE
영역 기능 태그 TLD Prefix
Core
EL 지원catchoutremoveset
/jstl-c c조건 반복
choosewhenotherwise
forEachforTokensif
URL 처리
importparam
redirectparam
urlparam
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
JSTL XML
영역 기능 태그 TLD Prefix
XML
기본outparseset
/jstl-x x조건/반복
choosewhenotherwise
forEachif
변환transformparam
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
JSTL FORMATTING
영역 기능 태그 TLD Prefix
I18n
Locale 지정 setLocalerequestEncoding
/jstl-fmt fmt메시지
bundlemessage
paramsetBundle
숫자/날짜 형식
formatNumberformatDateparseDateparseNumbersetTimeZonetimeZone
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
JSTL SQL
영역 기능 태그 TLD Prefix
Database
setDataSource
/jstl-sql sql
SQL
querydateParamparamtransaction
update dateParamparam
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
Java Server Faces 개요
?JSF에 정의된 태그로 jsp에서 서버측 웹UI구현
?사용 객체:?컴포넌트 객체; JSP 에서 태그로 매핑
?이벤트 리스너와 밸리데이터;컴포넌트에 등록됨.
?모델 객체; 컴포넌트의 데이터와 어플리케이션기능 캡슐화.
?핵심 기능?컴포넌트 관리, 컴포넌트 데이터 처리, 사용자 입
력 검증, 이벤트 핸들링에 대한 강력한 지원 구조
JSF 구성요소
?서블릿 컨테이너에서 동작하며,
?구성요소?자바빈즈 컴포넌트 (JSF 기술; 모델 객체);
어플리케이션 기능과 데이터 포함
?이벤트 리스너
?태그 라이브러리
? JSP 페이지
?서버측 헬퍼 클래스, 예: 데이터베이스 액세스 빈
?추가 지원 요소?페이지에 UI 컴포넌트 렌더링하는 커스텀 태그 라이브러리
?서버의 상태 객체를 나타내는 UI 컴포넌트
?밸리데이터, 이벤트 핸들러, 네비게이션 핸들러
JSF 동작원리
브라우저
Java server
myform.jsp
myUI
페이지요청HTTP request
HTTP responseHTML생성
JSF 동작구조
JSF 설치
?Download – EarlyAccess2?http://java.sun.com/j2ee/javaserverfaces/dow
nload.html
?server.xml 의 <Host> 에서unpackWARs="true" 로 설정, 재기동?샘플 WAR 파일 webapps 로 복사 후
?http://localhost:8080/<war파일명>/으로접속
JSF 실행 예제
greeting.jsp
<HTML><HEAD> <title>Hello</title> </HEAD>
<%@ taglib uri="http://java.sun.com/j2ee/html_basic/" prefix="faces" %>
<body bgcolor="white"><img src="/helloDuke/wave.med.gif">
<h2>My name is Duke. What is yours?</h2>
<jsp:useBean id="UserNameBean" class="helloDuke1.UserNameBean" scope="session" />
<faces:usefaces><faces:form id=" helloForm" formName="helloForm" >
<faces:textentry_input id="username"
modelReference="UserNameBean.userName"/><faces:command_button id="submit" commandName="submit" />
</faces:form>
</faces:usefaces></HTML>
JSF 실행 예제
output<HTML>
<HEAD> <title>Hello</title> </HEAD>
<body bgcolor="white"><img src="/helloDuke/wave.med.gif"><h2>My name is Duke. What is yours?</h2>
<FORM METHOD="post" ACTION="/helloDuke/faces/greeting.jsp;jsessionid=DDCD2ED4EC5DE3EDC0222E38770DB06A"><INPUT TYPE="text" NAME="/helloForm/username"><INPUT TYPE="SUBMIT" NAME="submit" VALUE="submit"></FORM>
</HTML>
Simple Tag Handler
?단순해진 태그라이브러리 구성
?EL 과 같이 사용
?Tag 함수의 사용
Simple Tag Handler 예제
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.util.HashMap;
/*** SimpleTag handler that accepts a
num attribute and * invokes its body 'num' times.*/public class RepeatSimpleTag
extends SimpleTagSupport {private int num;
public void doTag() throws JspException, IOException {
HashMap params = new HashMap();
for (int i=0; i<num; i++) {params.put( "count",
String.valueOf( i + 1 ) );getJspBody().invoke(null,
params);}
}
public void setNum(int num) {this.num = num;}
}
Simple Tag Handler 예제
<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
<html><head><title>JSP 2.0 Examples - Repeat SimpleTag Handler</title> </head>
<body>
<p>The body of the tag is encapsulated in a "JSP Fragment" and passedto the tag handler, which then executes it five times, inside a
for loop. The tag handler passes in the current invocation in a
scoped variable called count, which can be accessed using the EL.</p><br><b><u>Result:</u></b><br>
<mytag:repeat num="5">
Invocation ${count} of 5<br></mytag:repeat>
</body>
</html>
Tag Files
?TLD 생략가능 helloWorld.tag 직접 접근
?.tag file 을 template 으로 사용?같은 template 을 다른 형태로 출력
Tag Files
?컴파일이 필요 없다. 핸들러 자동 생성
?파일위치: /WEB-INF/tags/helloWorld.tag
?Hello, world!
?helloWorld.java Tag Library 자동 생성
?in jsp:?<%@ taglib prefix="tags" tagdir="/WEB-
INF/tags" %><tags:helloWorld/>
Tag Files – 동적변화
panel.tag<%@ attribute name="color" %><%@ attribute name="bgcolor" %><%@ attribute name="title" %><table border="1" bgcolor="${color}">
<tr><td><b>${title}</b></td>
</tr><tr>
<td bgcolor="${bgcolor}"><jsp:doBody/>
</td></tr>
</table>
Tag Files – 동적변화
? jsp <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %><tags:panel color="#ff8080" bgcolor="#ffc0c0" title="Panel 1">First panel.<br/></tags:panel>
<tags:panel color="#8080ff" bgcolor="#c0c0ff" title="Panel 3">Third panel.<br/>
<tags:panel color="#ff80ff" bgcolor="#ffc0ff" title="Inner">A panel in a panel.</tags:panel>
Third panel.<br/></tags:panel>
Tag Files 결과
Tag Files - <jsp:invoke>
? 동적 tag 의 생성<%@ attribute name="normalPrice" fragment="true" %>
<%@ variable fragment="normalPrice" name-given="name" %><%@ variable fragment="normalPrice" name-given="price" %>
…<table border="1">
<tr><td>
<jsp:invoke fragment="normalPrice"><jsp:param name="name" value="Hand-held Color PDA"/><jsp:param name="price" value="$298.86"/></jsp:invoke>
</td>…
Tag Files - <jsp:invoke>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<tags:displayProducts>
<jsp:attribute name="normalPrice">
Item: ${name}<br/>
Price: ${price}
</jsp:attribute>…
<h2>Products (Same tag, alternate style)</h2>
<tags:displayProducts>
<jsp:attribute name="normalPrice">
<b>${name}</b> @ ${price} ea.
</jsp:attribute>
JSP Property Groups
Context 별, 패턴별로 jsp 관리 가능
•Indicate that a resource is a JSP file (implicit).•Control enabling of EL evaluation.•Control enabling of Scripting elements.
Scripting elements ( <%@, <%!, <%=, <% ) are disallowed here. 에러
•Indicate pageEncoding information.•Prelude and Coda automatic includes.
JSP Property Groups
<jsp-config>
<jsp-property-group><description>
Special property group for JSP Configuration JSP example.
</description><display-name>JSPConfiguration</display-name>
<url-pattern>/jsp2/misc/config.jsp</url-pattern>
<el-ignored>true</el-ignored><page-encoding>ISO-8859-1</page-encoding>
<scripting-invalid>true</scripting-invalid>
<include-prelude>/jsp2/misc/prelude.jspf</include-prelude><include-coda>/jsp2/misc/coda.jspf</include-coda>
</jsp-property-group>
</jsp-config>
동적 속성 Dynamic Attributes jsp
?커스텀태스에서 속성의 이름과 개수를 동적으로 받아들임
<h2>Invocation 1 (six attributes)</h2><ul><my:echoAttributes x="1" y="2" z="3" r="red" g="green" b="blue"/>
</ul><h2>Invocation 2 (zero attributes)</h2><ul><my:echoAttributes/>
</ul><h2>Invocation 3 (three attributes)</h2><ul><my:echoAttributes dogName="Scruffy"
catName="Fluffy"blowfishName="Puffy"/>
</ul>
동적 속성 Dynamic Attributes handler
import javax.servlet.jsp.tagext.DynamicAttributes;
public class EchoAttributesTagextends SimpleTagSupportimplements DynamicAttributes
private HashMap attributes = new HashMap();
public void setDynamicAttribute( String uri, String localName, Object value ) throws JspException {
attributes.put( localName, value ); }
동적 속성 Dynamic Attributes tld
? TLD – dynamic-attributes 엘리먼트
<tag>
<description>
Tag that echoes all its attributes and body content
</description>
<name>echoAttributes</name>
<tag-class>jsp2.examples.simpletag.EchoAttributesTag</tag-class>
<body-content>empty</body-content>
<dynamic-attributes>true</dynamic-attributes>
</tag>
참고
? JSTL in Action by Alex Garrett
? http://www.codercoop.com/Members/alex_garrett/jstlnewapproach
? Java Web Services Tutorial? EL http://java.sun.com/webservices/docs/1.0/tutorial/doc/JSTL4.html#65865? JSTL http://java.sun.com/webservices/docs/1.0/tutorial/doc/JSTL.html#74644? JSF http://java.sun.com/j2ee/javaserverfaces/docs/tutorial.html
? 톰캣 http://jakarta.apache.org/tomcat? 스펙 다운로드
JSP http://java.sun.com/products/jsp/download.htmlServlet http://java.sun.com/products/jsp/download.html
? JSTL 1.0 by Hans Bergsten
? Standardizing JSP, Part 1 http://www.onjava.com/pub/a/onjava/2002/08/14/jstl1.html
? What JSP Applications Need, Part 2 http://www.onjava.com/pub/a/onjava/2002/09/11/jstl2.html
? What JSP Applications Need, Part 3 http://www.onjava.com/pub/a/onjava/2002/10/30/jstl3.html
참고
? CVS? http://www.cvshome.org/? http://www.cvsnt.org/? http://sourceforge.net/projects/cvsgui/? http://jakarta.apache-korea.org/seoul/how-to-SF-CVS.html
? SPEC
? jsp 2.0 http://jcp.org/aboutJava/communityprocess/first/jsr152/index.html
? jstl 1.0 http://jcp.org/aboutJava/communityprocess/final/jsr052/? jsf ea draft 1.0
http://java.sun.com/j2ee/javaserverfaces/download.html? 다국어
? http://iasandcb.pe.kr/2g/multilingualism/index.html? http://java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html? http://www.iana.org/assignments/character-sets? 브라우저 인코딩
? http://210.219.132.169/bbs?act=VIEW&seq=27108&bbs=bbs4