05.JSP2009. 1. 19. 10:10
반응형
오픈 소스 스터디
Added by 박재성, last edited by Jang Jooran on 4월 03, 2006  (view change)
Labels:
(None)

JSTL과 Velocity를 활용한 UI 레이어 구현 방법

Table of Contents

JSTL

소개

  • J2EE 소형 클라이언트 기술인 JSP(JavaServer Pages)가 지난 몇 년 동안 널리 일반화되면서 독립적인 개발자들은 많은 사용자 정
    의 JSP 태그 라이브러리를 만들었습니다. 이러한 태그 라이브러리는 대부분 서로 다른 목표를 달성하도록 작성되었지만 반복, 조건 등의 일
    반적인 작업을 위한 유사한 솔루션을 제공하는 경향이 있습니다.
    유사하고 일반적이 문제점을 해결하는 독립적인 태그 라이브러리에 대한 필요성을 줄이기 위해 Java Community Process(JSR 52)의 지
    원하에 JSTL(JavaServer Pages Standard Tag Library)이 개발되었습니다. JSTL은 이러한 일반 기능을 처리하는 하나의 표준 솔루션
    을 제공합니다. (말그대로 표준태그라이브러리)
  • JSTL의 주요 강점 중 하나는 서블릿 컨텍스트에 저장된 데이타 같은 애플리케이션 데이타를 액세스 및 조작하는 쉬운 방법을 제공하는 간
    단한 EL을 사용할 수 있다는 것입니다.

EL 에 대하여

설치 방법

  • http://cvs.apache.org/builds/jakarta-taglibs/nightly/ 에서 다운
    \jakarta-taglibs-20051024\jakarta-taglibs\standard\lib
    에서 jstl 과 standard 파일 을 이 두개의 jar 파일을 우리의 웹애플리케이션의 /WEB-INF/lib 폴더에 넣습니다
    그 다음 tld 폴더의 tld 파일을 /WEB-INF/lib/tld 폴더 아래 넣습니다.
  • web.xml 에
     
        <!-- jstl 1.2 taglig -->
         <taglib>
           <taglib-uri>jstl-c</taglib-uri>
           <taglib-location>/WEB-INF/tlds/jstl/c.tld</taglib-location>
        </taglib>
        <taglib>
           <taglib-uri>jstl-fmt</taglib-uri>
           <taglib-location>/WEB-INF/tlds/jstl/fmt.tld</taglib-location>
        </taglib>
        <taglib>
          <taglib-uri>jstl-fn</taglib-uri>
          <taglib-location>/WEB-INF/tlds/jstl/fn.tld</taglib-location>
        </taglib>
        

    를 추가한다.

  • jsp 에 추가
     
         <%@ taglib uri="jstl-c" prefix="c" %>
        <%@ taglib uri="jstl-fmt" prefix="fmt" %>
        <%@ taglib uri="jstl-fn" prefix="fn" %>
         

사용 예(기본 문법)

Area Subfunction Prefix Description
Core Variable support c 변수지원
Core Flow control c 흐름제어
Core URL management c URL 처리
Core Miscellaneous c  
XML Core x XML 코어
XML Flow control x 흐름 제어
XML Transformation x XML 변환
I18n Locale fmt 지역
I18n Message formatting fmt 메시지 형식
I18n Number and date formatting fmt 숫자 및 날짜 형식
Database SQL sql SQL
Functions Collection length fn 콜렉션 처리
Functions String manipulation fn String 처리

http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html 참고

  • 변수지원태그
    set: <c:set var="varName" scope="session" value="someValue">
    var속성은 값을 지정할 변수의 이름
    <c:set t a r g e t ="" property="userName" value="someValue">
    target : 빈 프로퍼티나 맵 값을 설정한다.(Object)
    var와 target을 동시에 사용할 수 없다.
    scope속성은 변수가 위치하는 영역(page,request,session,application)
    value :저장하는 값
    remove :<c:remove var="varName" scope="session">
    var :삭제할 변수의 이름
    scope 속성은 삭제할 변수의 영역
    out : <c:out value="">
    value속성은 출력하려는 값
    catch : <c:catch var="">
    </c:catch>
    예외사항이 한번이라도 발생시 </c:catch>로 점프
    var에 정의 된 객체를 페이지 생존범위에 자동으로 묶어 나중에 var에 정의된 변수이름을 사용할 수 있다.
    예외 발생시
    : var 속성 사용시 exception 객체를 설정.
    <c:catch> 문 밖으로 제어가 떨어진다
 
    <c:set var="num1" value="${20}" />
	<c:set var="num2">
		10.5
	</c:set>
	
	<c:set var="today" value="<%= new java.util.Date()%>" /><br>

	변수 num1 = ${num1} <br>
	변수 num2 = ${num2} <br>
	num1 + num2 = ${num1+num2}<br>
	오늘은 ${today}입니다.
	
	<c:remove var="num1" scope="page" />
	
	<p>
	삭제한 후의  num1=${num1} <br>
	삭제한 후의 num1 + num2 = ${num1 + num2}
   
 
       <c:catch var="myException">
     	It's catch
         <% int x = 10/0; %>
         실행안됨.
       </c:catch>
       <c:if test="${myException != null}">
           발생된 예외는 : ${myException.message} <br>
       </c:if>
     
  • URL 관련
    import : <c:import url=""/>
    url속성에 명기한 파일을 현재 컨텐츠에 포함
    param : <c:param name="" value=""/>
    <jsp:param />과 같은 역할
    url : <c:url value="" var=""/>
    value에 들어있는 상대 경로 뒤에 jsessionid를 추가한다.(쿠키를 사용 못하는 경우)
    var : 옵션 속성으로 url을 참조하기 위해쓴다.
    redirect :<c:redirect url="' context=""/>
    context : url경로의 이름
 
    <c:import url="Header.jsp" >
	<c:param name="subTitle" value="This is subTitle"/>
    </c:import>
   
  • 흐름제어 태그
    if : <c:if test="조건"> </c:if>
    test속성의 값에는 "조건"이 오는데 이 조건문의 결과값이 true 면 처리
     
       <c:if test="true">
         무조건 수행<br>
        </c:if>
    
        <c:if test="${param.name == 'bk'}">
          name 파라미터의 값이 ${param.name}입니다 <br>
        </c:if>
    
        <c:if test="${param.name eq 'bk'}">
          name 파라미터의 값이 ${param.name}입니다 <br>
        </c:if>
    
        <c:if test="${18 < param.age}">
    	 당신의 나이는 18세 이상입니다.
        </c:if>   
       

    choose,when,otherwise : <c:choose>
    <c:when test="조건">
    </c:when>
    <c:otherwise>
    </c:otherwise>
    </c:choose>
    choose 태그는 자바의 switch 문과 if-else 의 혼합한 형태, 다수의 조건문을 하나의 블록에서 수행하고자 할때 사용
    -> switch문과의 차이점은 중간에 빠져 나가지 못한다는 것이다.
    -> when 의 어느 하나에도 실행되지 않을때 otherwise 실행
    -> otherswise 태그가 반드시 있어야 하는것은 아니다.

 
     <c:choose>
       <c:when test="${param.name == 'bk' }">
	<li>당신의 이름은 ${param.name}입니다.
     </c:when>
     <c:when test="${param.age > 18 }">
	<li>당신은 18세 이상입니다.
     </c:when>

     <c:otherwise>
	<li> 당신은 'bk'가 아니고 18세 이상이 아닙니다.
     </c:otherwise>
     </c:choose> 
    

forEach : <c:forEach var="변수" items="아이템" begin="시작값" end="끝값" step="증가값">
</c:forEach>
item 속성에 올수 있는 것들로는 Map,배열,Collection 이 있다.
varStatus는 javax.servlet.jsp.jstl.core.LoopTagStatus 객체 인스턴스변수를 만들며 count라는 프로퍼티가 있어 몇번의 회전인지 알 수있다.

 
       <c:forEach var="i" begin="1" end="9">
	<li>4 *${i} = ${4 *i}
       </c:forEach>

       <h4>int 형 배열</h4>

       <c:forEach var="i" items="${intArray}" begin="2" end="4">
	[${i}]
       </c:forEach>

       <h4>Map</h4>
       <c:forEach var="i" items="${map}">
	  ${i.key} = ${i.value}<br>
       </c:forEach>

       <c:forEach var="member" items="${memberList}" varStatus="memberLoopCount">
	  회원 $(memberLoopCount.count} : ${member} <br>
       </c:forEach>
     

forTokens : <c:forTockens var="token" items="문자열" delins="구분자">
</c:forTockens>
forTokens 태그는 StringTokenizer 와 같은 기능을 제공한다.

 
       <c:forTokens var="token" items="빨강색, 주황색, 노란색, 초록색, 파랑색, 남색, 보라색" delims=",">
     	${token}<br>
       </c:forTokens>
     
  • 숫자 및 날짜 지원 형식
    The JSTL formatting actions allow various data elements in a JSP page, such as numbers,dates and times
    to be formatted and parsed in a locale-sensitive or customized manner.

formatNumber : 숫자 형식을 표현

 
 
      number  : <fmt:formatNumber value="9876543.61" type="number"/>
      currency: <fmt:formatNumber value="9876543.61" type="currency"/>
      percent : <fmt:formatNumber type="percent">9876543.61</fmt:formatNumber>

      pattern=".000"    :<fmt:formatNumber value="9876543.61" pattern=".000" />
      pattern="#,#00.0#":<fmt:formatNumber value="9876543.612345" pattern="#,#00.0#"/>
    

parseNumber : 정해진 패턴을 문자열에서 수치를 파싱해내는 태그
formatDate :날짜 형식을 표현

 
      <jsp:useBean id="now" class="java.util.Date"/>
	
         <c:out value="${now}"/>
           date: <fmt:formatDate value="${now}" type="date"/>
           time: <fmt:formatDate value="${now}" type="time"/>
           both: <fmt:formatDate value="${now}" type="both"/>

           default:<fmt:formatDate value="${now}"
                        type="both" dateStyle="default" timeStyle="default"/>
           short  :<fmt:formatDate value="${now}"
                        type="both" dateStyle="short"   timeStyle="short"  />
           medium :<fmt:formatDate value="${now}"
                        type="both" dateStyle="medium"  timeStyle="medium" />
           long   :<fmt:formatDate value="${now}"
                        type="both" dateStyle="long"    timeStyle="long"   />
           full   :<fmt:formatDate value="${now}"
                        type="both" dateStyle="full"    timeStyle="full"   />

          pattern="yyyy년MM월dd일 HH시mm분ss초"
             <fmt:formatDate value="${now}" type="both"
                             pattern="yyyy년MM월dd일 HH시mm분ss초"/>
            
         <fmt:formatDate value="${now}" pattern="yyyy/MM/dd" />

parseDate :정해진 패턴의 문자열에서 날짜를 파싱해내는 태그
timeZone : <fmt:timeZone value=""/>

setTimeZone : <fmt:timeZone value="" var="" scope=""/>

  • 국제화
    message <fmt:message
    setLocale <fmt:setLocale
    bundle <fmt:bundle
    setBundle <fmt:setBundle
    param <fmt:param
    requestEncoding <fmt:requestEncoding
  • SQL
    <sql:query sql="sqlQuery" var="varName" [scope="{page|request|session|application}"]
    [dataSource="dataSource"] [maxRows="maxRows"] [startRow="startRow"]>
    <sql:param>
    </sql:query>
         <sql:query var="customers" dataSource="${dataSource}">
          SELECT * FROM customers
          WHERE country ='China'
          ORDER BY lastname
         </sql:query>
         
         <table>
          <c:forEach var="row" items="">
             <tr>
               <td><c:out value="${row.lastName}"/></td>
               <td><c:out value="${row.firstName}"/></td>
               <td><c:out value="${row.address}"/></td>
             </tr>
          </c:forEach>
         </table>
       

<sql:update>
<sql:setDataSource>
<sql:param>
<sql:dateParam>

  • XML 코어
    <x:parse>
    <x:out>
    <x:set>
  • 흐름제어
    <x:if>
    <x:choose>
    <x:when>
    <x:otherwise>
    <x:forEach>
  • XML 변환
    <x:transform>
    <x:param>
  • function
    contains
    containsIgnoreCase
    endsWith
    escapeXml
    indexOf
    join
    length
    replace
    split
    startsWith
    substring
    substringAfter
    substringBefore
    toLowerCase
    toUpperCase
    trim
         <c:if test="${fn:contains(name, searchString)}">
         <c:if test="${fn:containsIgnoreCase(name, searchString)}">
         <c:if test="${fn:endsWith(filename, ".txt")}">
         ${fn:escapeXml(param:info)}
         ${fn:indexOf(name, "-")}
         ${fn:join(array, ";")} 
         You have ${fn:length(shoppingCart.products)} in your shopping cart.
         ${fn:replace(text, "-", "•")}
         ${fn:split(customerNames, ";")}
         <c:if test="${fn:startsWith(product.id, "100-")}">
         P.O. Box: ${fn:substring(zip, 6, -1)}
         P.O. Box: ${fn:substringAfter(zip, "-")}
         Zip (without P.O. Box): ${fn:substringBefore(zip, "-")}
         Product name: ${fn.toLowerCase(product.name)}
         Product name: ${fn.UpperCase(product.name)}
         Name: ${fn.trim(name)}
       

Velocity

Velocity

소개

  • 벨로시티란 자바 기반의 템플릿 엔진입니다.
    벨로시티를 활용하면 간단하면서도 강력한 템플릿 언어를 통하여 자바 코드에 정의된 객체를 액세스할 수 있습니다.
    벨로시티를 웹 개발에 사용하면, 웹 디자이너는 자바 프로그래머와 병렬로 작업을 할 수 있으며 MVC(모델-뷰-컨트롤러) 모델에 따라 웹 사이트를 개발할 수 있습니다. 더 자세히 설명하면 웹 페이지 디자이너의 경우 보기 좋은 사이트를 만드는 데만 집중하면 되고, 프로그래머는 잘 동작하는 코드를 만드는 데만 집중하면 된다는 뜻입니다.
    벨로시티는 웹 페이지와 자바 코드를 분리하여, 장기적인 측면에서 볼 때 웹 사이트를 손쉽게 유지보수할 수 있도록 하고, 자바 서버 페이지 (JSP) 또는 PHP를 대체할 수 있는 방안을 제시합니다. 벨로시티의 쓰임새는 웹 사이트에 국한되지 않습니다. 예를 들면, 템플릿으로부터 SQL이나 포스트스크립트, 또는 XML(XML 변환에 대해서는 벨로시티 툴 중 하나인 아나키아(Anakia)를 참조)문서를 생성하는 데 쓰일 수 있습니다. 벨로시티는 스탠드얼론 유틸리티처럼 사용하여 소스 코드나 리포트를 생성할 수도 있고, 다른 시스템의 컴포넌트로 통합할 수도 있습니다. 또한 벨로시티는 터빈 (또다른 자카르타 서브 프로젝트 중 하나) 웹 애플리케이션 프레임웍에 템플릿 서비스를 제공합니다. 벨로시티와 터빈을 조합하면 진정한 MVC 모델에 따라 웹 애플리케이션을 개발할 수 있습니다

설치 방법

  • web.xml 수정
     
       <servlet>
         <servlet-name>velocity</servlet-name>
            <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet
         </servlet-class>
         <init-param>
            <param-name>org.apache.velocity.toolbox</param-name>
            <param-value>/WEB-INF/velocity-toolbox.xml</param-value>
         </init-param>
         <init-param>
            <param-name>org.apache.velocity.properties</param-name>
            <param-value>/WEB-INF/velocity.properties</param-value>
           </init-param>
         <load-on-startup>10</load-on-startup>
       </servlet>
       <servlet-mapping>
          <servlet-name>velocity</servlet-name>
          <url-pattern>*.vm</url-pattern>
       </servlet-mapping>
     
  • 파일 생성
    velocity.properties 파일
    velocity-toolbox.xml 을 생성 한 후 web_inf/lib 아래 둡니다.
    velocity-toolbox.xml
    <tool>
       <key>date</key>
       <scope>application</scope>
       <class>org.apache.velocity.tools.generic.DateTool</class>
     </tool>
    
      <tool>
      <key>math</key>
      <scope>application</scope>
      <class>org.apache.velocity.tools.generic.MathTool</class>
    </tool>
     ...
    

사용 예(기본 문법)

Velocity Template Language(VTL) 은 Template 에서 사용되는 Velocity 고유의 언어를 의미합니다.

  • References(참조형)
    Variables(변수) - 다음과 같이 $를 먼저 쓰고 그 뒤에 식별자를 적어주는 방식으로 사용
    ex) $foo
    Property(특성) - $ 다음에 식별자를 쓰고, 마침표(.)후에 다시 식별자의 형태로 사용
    ex) $foo.name
    Method(메소드) - $다음에 식별자를 쓰고 마침표 후에 호출할 메소드의 이름을 적는다
    ex)$foo.getName()
  • Directive(지시형)
    #set - reference 의 값을 설정한다.
    #if/elseif/else - 조건문 제어
    #foreach ---- 제어
    #include - velocity 로 파싱되지 않는 파일의 출력
    #parse -velocity 로 파싱된 파일 출력
    #stop -template 엔진의 정지
    #macro - 반복적으로 사용할 vm정의
  • Comment (주석)
      ## - 한줄짜리 주석
      #* ... *# 여러줄 짜리 주석
      
     ##This is an example velocity template
     #set($this = "Velocity")
       $this is great! But It's so hard.

     #foreach($name in $list)
       $name is great!
     #end

     #set($condition = true)
     #if ($condition)
        The condition is true!
     #else
       The condition is false
     #end
  

http://jakarta.apache.org/velocity/docs/vtl-reference-guide.html

Tool box 에 대해

VelocityTools is a collection of Velocity subprojects with a common goal of creating tools and infrastructure for building both web and non-web applications using the Velocity template engine.

  • Generic Tool (http://jakarta.apache.org/velocity/tools/generic/)
    *DateTool : A tool for manipulating and formatting dates
    *MathTool :A tool for performing floating point math.
    *NumberTool :A tool for formatting numbers
    *IteratorTool :A convenience tool to use with #foreach loops. It wraps a list to let the designer specify a
    condition to terminate the loop, and reuse the same list in different loops.
    *RenderTool:A tool to evaluate and render arbitrary strings of VTL (Velocity Template Language).
          Example uses:
      $date                         -> Oct 19, 2003 9:54:50 PM
      $date.long                    -> October 19, 2003 9:54:50 PM PDT
      $date.medium_time             -> 9:54:50 PM
      $date.full_date               -> Sunday, October 19, 2003
      $date.get('default','short')  -> Oct 19, 2003 9:54 PM
      $date.get('yyyy-M-d H:m:s')   -> 2003-10-19 21:54:50
     
      $myDate                        -> Tue Oct 07 03:14:50 PDT 2003
      $date.format('medium',$myDate) -> Oct 7, 2003 3:14:50 AM 
    
    
        
  • VelocityView (http://jakarta.apache.org/velocity/tools/view/)

JSTL 과 Velocity

같은 로직에 대해 두가지를 사용하여 각각 구현

다양한 View Technology에 대한 실행 속도 비교.

현재 개발중 우리들이 많이 사용하는 View 기술들을 이용하여 실행속도를 비교해 보면 다음 그래프와 같다.

이 그래프는 100명의 동시 접속자에 대한 테스트를 진행한 결과이다. 이 그래프는 Expert One-on-One J2EE Design and Development 책의 Chapter 15의 Web-Tier Performance Issues에서 인용하였다.

위와 같이 테스트를 진행한 결과 JSP는 초당 54페이지, Velocity는 초당 112페이지, XMLC는 초당 128 페이지, XSLT는 6,7페이지를 서비스하였다. 이 부분에서 눈여겨 볼 부분은 Velocity에 대한 결과라할 수 있다. 국내에서는 아직까지 많이 사용되지 않는 기술이지만 위의 실행 결과를 보면 사용할만한 가치가 있다는 것을 확인할 수 있다.

참고문헌

문서에 대하여

최초작성자 : 박재성
최초작성일 : 2005년 10월 15일
버전 : 1.0
문서이력 :

  • 2005년 10월 15일 박재성 문서 최초 생성 : 강좌 문서 템플릿 및 JSP와 Velocity에 대한 속도 비교문서 추가

velocity 좋군요..

Posted by Anonymous at 9월 23, 2005 10:15

몰라서리.. test

Posted by 장회수 at 10월 18, 2005 19:25

언니~~ 기대 만땅~~ ^^

Posted by Jang Jooran at 11월 01, 2005 12:29

me too

Posted by 박재성 at 11월 01, 2005 12:30

아니 저사람은 누군데...
왜 하필... 내 발표자료에 이런짓을 자꾸 하는 거져... ㅠㅠ
속상하게... –

  • 수영 -
Posted by Anonymous at 1월 09, 2006 08:38
Site running on a free Atlassian Confluence Open Source Project License granted to JavaJiGi Project. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.3.1 Build:#643 1월 22, 2007) - Bug/feature request - Contact Administrators
Posted by 1010