'Language/JSP'에 해당되는 글 49건

  1. 2019.09.11 [URI] 한국어가 어떻게 URL에서 Percent-encoding 될까?
  2. 2014.11.14 JSTL 정리
  3. 2014.11.14 JSTL: fn
  4. 2014.11.14 JSTL: fmt
  5. 2014.11.14 JSTL: core
  6. 2014.11.14 JSTL
  7. 2014.11.11 JSP 게시판 구현 시 Paging 처리 하기
  8. 2014.11.11 JSP 내장 기본 객체의 영역(scope)
  9. 2014.11.11 exception 내장 객체
  10. 2014.11.11 page 기본 객체

[URI] 한국어가 어떻게 URL에서 Percent-encoding 될까?

Language/JSP 2019. 9. 11. 14:59

환경 및 선수조건

  • Percent-encoding의 개념
  • Character Set이 무엇인지

 

Character Set(Character encoding)이란?

  • Character Set(문자셋) 그리고 Character encoding(문자 인코딩)은 같은 말로 쉽게 말해서 어떤 인코딩 시스템에 의해서 존재하는 문자들을 표현하려는 방법을 의미한다.
  • ASCII나 Unicode가 문자 인코딩들의 대표적으로 알려진 예시입니다.

 

Percent-encoding이란?

  • Percent-encoding이란 URI 혹은 URL에 문자를 표현하는 인코딩 방식으로 RFC 3986에 따라서 알파벳이나 숫자 등 몇몇 문자를 제외한 문자들에 대해서 옥텟 값으로 묶어서 16진수 값으로 코딩하는 방식
  • 예시 : "/internet url" -> "internet%20url"

 

Percent-encoding의 방법

  • RFC3986문서를 찾아보면 정해진 몇몇개의 문자들을 제외하고는 octet(8bit가 한데 모인 것)으로 인코딩한 후에 %를 붙여서 인코딩 한다고 나와있다.
  • 여기서 한국어는 octet(8bit가 한데 모인 것)으로 변형되어서 표시되며 Unicode에 따라서 UTF-8 방식으로 바뀌어서 인코딩 되게 됩니다.

 

즉, 다시 정리하면

  • “한국어” -(UTF-8에 따라서)-> “코드화된 한국어” -(1바이트마다 %를 붙임)-> “퍼센트 인코딩된 한국어”
  • 예시 : “각” -(UTF-8에 따라서)-> “0xEA 0xB0 0x81” -(1바이트마다 %를 붙임)-> “%EA%B0%81”

 

예시

  • “각”의 경우

/각 => /%EA%B0%81

  • “선”의 경우

/선 => /%EC%84%A0

  • “꿳”의 경우

/꿳 => /%EA%BF%B3

 

참고자료

 

참조 - https://twpower.github.io/123-how-to-encode-korean-to-percent-encoding

 

'Language > JSP' 카테고리의 다른 글

JSTL 정리  (0) 2014.11.14
JSTL: fn  (0) 2014.11.14
JSTL: fmt  (0) 2014.11.14
JSTL: core  (0) 2014.11.14
JSTL  (0) 2014.11.14
:

JSTL 정리

Language/JSP 2014. 11. 14. 17:41


설정

web.xml

 

<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" %>


EL#

  1. 생존범위 속성 맵

    1. pageScope
    2. requestScope
    3. sessionScope
    4. applicationScope
  2. 요청 파라미터 맵

    1. param
    2. paramValues
  3. 요청 헤더 맵

    1. header
    2. headerValues
  4. 쿠키 맵

    1. cookie
  5. 컨텍스트 초기화 파라미터 맵(서블릿 초기화 파라미터 아님)

    1. initParam
  6. 실제 pageContext 객체에 대한 참조. 이것은 빈임

    1. pageContext

      1. pageContext 접근자

        1. getErrorData()
        2. getPage()
        3. getRequest()
        4. getResponse()
        5. getServletConfig)()
        6. getServletContext()
        7. getSession()
      2. JspContext로 부터 상속받은 접근자

        1. getAttribute()
        2. getAttributeNamesInScope()
        3. getAttributesScope()
        4. getExpression!Eval!uator()
        5. getOut()
        6. getVariableResolver()



스크립팅

  1. <$= request.getHeader("host") %>

EL 내장 객체

  1. ${header["host"]}
  2. ${header.host}
  3. ${headerValues.host[]}


스크립팅

  1. <%= request.getMethod() %>

EL 내장 객체

  1.  ${pageContext.request.method}

 

core

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

  • 일반적인 것

    • <c:out>
    • <c:set>
    • <c:remove>
    • <c:catch>
  • 조건

    • <c:if>
    • <c:choose>
    • <c:when>
    • <c:otherwise>
  • URL 관련

    • <c:import!>
    • <c:url>
    • <c:redirect>
    • <c:param>
  • 반복

    • <c:forEach>
    • <c:forEachToken>


① set


     - JSP의 setAttribute()와 같은 역활
     - 기본형
       <c:set   var="변수명"
                    value="변수명에 할당된 값"
                    target="자바빈 객체명이나 Map 객체명"
                    property="자바빈 객체나 Map 객체의 값을 설정할 프로퍼티 명"
                    scope="변수의 공유 범위(유효기간)으로 page|request|session|application" />
     - 예제
          <c:set var="country" value="${'Korea'}" />
          <c:set var="intArray" value="<%=new int[] {1,2,3,4,5}%>" />
          <c:set var="sum" value="${sum+i}" />
 
② out


     - JSP의 표현식을 대체하는 것으로 많이 사용됨
     - 기본형
          <c:out var="변수명"
                    default="기본값"
                    escapeXML="true|false" />
 
     * escapeXML
     > 생략시 기본값은 true
     > true일 경우 값 중에 포함된 <>&'" 문자들을 각각 <, >, &, ', "로 출력

     - 예제
          <c:out value="${sum}" />
          <c:out value="${val}" />
 
③ remove


     - JSP의 removeAttribute()와 같은 역활
     - 기본형
          <c:remove var="변수명"
                              scope="변수의 공유 범위로 page(생략 시 기본)|request|session|application" />
     - 예제
          <c:remove var="browser" />
 
④ catch


     - body 위치에서 실행되는 코드의 예외를 잡아내는 역할
     - 기본형
          <c:catch var="에러가 발생할 때 에러 메세지가 포함될 변수명" />
     - 예제
          <c:catch var="errmsg">
               line 1~
               <%=1/0%>
               line 2~
          </c:catch>
          <c:out value="${errmsg}" />
 
⑤ if


     - 조건문에 사용
     - 기본형
          <c:if   test="조건 판별식"
                    var="변수명"
                    scope="변수의 공유범위 page|request|session|application"
     - 예제
          <c:if test="${country != null}">
               국가명 : <c:out value="${country}" />
          </c:if>
 
⑥ choose


     - 자바의 switch문과 동일
     - 조건에서 문자열 비교가 가능
     - 하나 이상의 <when>과 하나의 <otherwise> 서브 태그를 가짐
 
⑦ when


     - choose 태그의 서브태그
     - choose 태그내에서 여러번 사용될 수 있다.
     - 기본형
          <c:when test="조건 판별식" />
 
⑧ otherwise


     - choose 태그의 서브태그
     - choose 태그내에서 한번만 사용될 수 있다.
     - 예제 :
          <c:choose>
               <c:when test="${country == 'Korea'}">
               나라 : <c:out value="${country}" />
          </c:when>
 
          <c:when test="${country == 'Canada'}">
               나라 : <c:out value="${country}" />
          </c:when>
   
          <c:otherwise>
               선택된 나라가 없습니다.
          </c:otherwise>
     </c:choose>
 
⑨ forEach


     - 객체 전체에 걸쳐 반복 실행할 때 사용
     - 기본형
          <c:forEach   items="반복할 객체명"
                              begin="시작값"
                              end="종료값"
                              step="증가값"
                              var="변수명"
                              varStatus="별도의 변수" />

⑩ forTokens


     - 문자열을 주어진 구분자(delimiter)로 분할
     - 기본형
          <c:forTokens items="반복할 객체명"
                              delims="구분자"
                              begin="반복할 시작값"
                              end="반목 마지막값"
                              step="증가값"
                              var="변수명"
                              varStatus="별도의 변수"
     - 예제
          <c:forTokens var="color" items="빨강색,주황색.노란색.초록색,파랑색,남색.보라색" delims=",.">
               color : <c:out value="${color}" /><br>
          </c:forTokens>
 
⑪ import!


 - 웹 어플리케이션 내부의 자원 및 http, ftp와 같은 외부에 있는 자원에 대해 접근
 - 기본형
  <c:import! url="읽어올 URL"
     var="읽어올 데이터를 저장할 변수명"
     scope="변수의 공유 범위"
     varReader="리소스의 내용을 Reader 객체로 읽어올 때 사용"
     charEncoding="읽어온 데이터의 캐릭터셋 지정" />
 
⑫ redirect


     - response.sendRedirect()를 대체하는 태그로 지정한 다른 페이지로 이동
     - 기본형
          <c:redirect url="이동할 URL" />
 
⑬ url


     - 쿼리 파라미터로 부터 URL 생성
     - 기본형
          <c:url var="생성한 URL이 저장될 변수명"
                    value="생성할 URL"
                    scope="변수의 공유 범위" />
 
⑭ param


     - 기본형
          <c:param name="파라미터 명"
                         value="파라미터 값" />
               <c:url var="registrationURL" value="/customers/register">
               <c:param name="name" value="${param.name}" />
               <c:param name="country" value="${param.country}" />
          </c:url>


<c:set var="temp" value="Hello! World" />
<c:out value="${ temp }" default="value is null"/><br>
<c:out value="${ temp }" default="value is null" escapeXml="false" /><br>
<c:out value="${ temp2 }" default="value is null" /><br>

<c:remove var="timezone" scope="session"/>
<c:set var="timezone" scope="session">CST</c:set>

<c:out value="${cookie['tzPref'].value}" default=="CST"/>

 

function
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

${fn:substring(name, 1, 10)}


fn:contains(string, substring)  
string이 substring을 포함하면 true 리턴. 

fn:containsIgnoreCase(string,substring)
대소문자에 관계없이, string이 substring을 포함하면 true 리턴. 

fn:endsWith(string, suffix)   
string이 suffix로 끝나면 true 리턴. 

fn:escapeXml(string)    
string에 XML과 HTML에서 특별한 의미를 가진 문자들이 있으면, XML 엔티티 코드로 바꿔준 뒤 문자열 리턴. 

fn:indexOf(string,substring)  
string에서 substring이 처음으로 나타나는 인덱스 리턴. 

fn:join(array, separator)
  
array(배열) 요소들을 separator를 구분자로 하여 연결해서 리턴 

fn:length(item)
      
item 이 배열이나 컬렉션이면 요소의 갯수를, 문자열이면 문자의 갯수를 리턴. 

fn:replace(string, before, after)
 
string 내에 있는 before 문자열을 after 문자열로 모두 바꿔서 리턴. 

fn:split(string, separator)
   
string 내의 문자열을 separator에 따라 나누어서 배열로 구성해 리턴. 

fn:startsWith(string, prefix)
  
string이 prefix로 시작하면 true 리턴. 

fn:substring(string, begin, end)
 
tring에서 begin 인덱스에서 시작해서 end 인덱스에 끝나는 부분
(end 인덱스에 있는문자 포함)의 문자열을 리턴.

fn:substringAfter(string, substring)

string에서 substring이 나타나는 이후의 부분에 있는 문자열을 리턴. 

fn:substringBefore(string, substring)

string에서 substring이 나타나기 이전의 부분에 있는 문자열을 리턴. 

fn:toLowerCase(string)
    
string을 모두 소문자로 바꿔 리턴. 

fn:toUpperCase(string)
    
string을 모두 대문자로 바꿔 리턴. 

fn:trim(string)
      
string 앞뒤의 공백(whitespace)을 모두 제거하여 리턴.


fmt

 

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

  • 국제화

    • <fmt:message>
    • <fmt:setLocale>
    • <fmt:setTimeZone>
    • <fmt:bundle>
    • <fmt:setBundle>
    • <fmt:param>
    • <fmt:requestEncoding>
  • 포맷팅

    • <fmt:timeZone>
    • <fmt:setTimeZone>
    • <fmt:formatNumber>
    • <fmt:formatDate>
    • <fmt:parseNumber>
    • <fmt:parseData>
    • <fmt:parseNumber>



jstl fmt로 날짜보여줄때, pattern attribute에 의한 날짜 표현 방식들

pattern="yyyy-MM-dd aa h:mm:ss"    
2007-12-13 오전 9:36:48

pattern="yyyy-MM-dd aa hh:mm:ss"  
2007-12-13 오전 09:36:48

pattern="yyyy-MM-dd H:mm:ss"      
2007-12-13 9:36:48

pattern="yyyy-MM-dd HH:mm:ss"    
2007-12-13 09:36:48


<fmt:setLocale value="fr_CA" scope="session"/>
<fmt:setTimeZone value="Australia/Brisbane" scope="session"/>

<fmt:formatDate value="${blogEntry.created}" dateStyle="full"/>
<c:out value="${blogEntry.title}" escapeXml="false"/>
<fmt:formatDate value="${blogEntry.created}" pattern="h:mm a zz"/>
<fmt:formatNumber value="0.02" type="currency" currencySymbol="원"/>

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

[type="{number|currency|percent}"]


<fmt:parseDate value="${usDateString}" parseLocale="en_US" type="both" dateStyle="short" timeStyle="short" var="usDate"/>

 

sql
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
  • 데이터베이스 접근

    • <sql:query>
    • <sql:update>
    • <sql:setDataSource>
    • <sql:param>
    • <sql:dataParam>



xml

<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

  • 코어 xml 액션

    • <x:parse>
    • <x:out>
    • <x:set>
  • xml 흐름 제어

    • <x:if>
    • <x:choose>
    • <x:when>
    • <x:otherwise>
    • <x:forEach>
  • 변환 액션

    • <x:transform>
    • <x:param>




출처 - http://tazz009.tistory.com/484

'Language > JSP' 카테고리의 다른 글

[URI] 한국어가 어떻게 URL에서 Percent-encoding 될까?  (0) 2019.09.11
JSTL: fn  (0) 2014.11.14
JSTL: fmt  (0) 2014.11.14
JSTL: core  (0) 2014.11.14
JSTL  (0) 2014.11.14
:

JSTL: fn

Language/JSP 2014. 11. 14. 17:39

Function, 함수

기능 : 컬렉션 처리,  String 처리

접두어(Prefix) : fn

directive : <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>


JSTL functions은 JSTL에서 제공하는 각종 함수를 사용해서 문자열이나, 컬렉션들을 처리한다.

fn태그는 단독으로 사용할 수 없고 EL 표현식 내에서 사용한다.


 boolean contains(String sting, String substring) : string이 substring을 포함하면 true값을  리턴 한다.

 boolean containsIgnoreCase(String string, String substring) : 대소문자에 관계없이, string이 substring을 포함하면 true 리턴

${fn:contains("helloworld", "world")} // true

${fn:containsIgnoreCase("hello world!", "WoRLd")} // true

      

● boolean startsWith(String string, String prefix) : string이 prefix로 시작하면 true값을 리턴 한다.

● boolean endsWith(String string, String substring) : string이 suffix로 끝나면 true값을 리턴 한다. 

${fn:startsWith("hello world!", "ld!")} // false

${fn:endsWith("hello world!", "ld!")} // true


● String escapeXml(String string)

 : string에서 XML, HTML의 < >& ' " 문자들을 각각 &lt; &gt; &amp; &#039; &#034;로 바꿔준 뒤 문자열을 리턴 한다. 

<c:out value="${fn:escapeXml('<>')}"/> // &lt;&gt;


● int indexOf( java.lang.String  string, java.lang.String  substring) 

 : string에서 substring이 처음으로  나타나는 인덱스를 리턴 한다.

${fn:indexOf("abcdefg", "f")} // 5


● String[] split(String string, String separator) : string 내의 문자열을 separator에 따라 잘라내서 잘려진 문자열들을 배열로 리턴한다.

● String join(String[], String separator) : 배열 요소들을 separator를 구분자로 하여 모두 연결해서 리턴 한다.

<c:set var="texts" value="${fn:split('Hi My name is waldo', ' ')}"/>

<c:out value="${fn:join(texts, '-')}"/> // Hi-My-name-is-waldo


// jstl이나 el에 문자열 리터럴로 배열을 직접 생성하는 예제는 검색결과가 없다. 대부분 fn:split이나 jsp:useBean을 사용했다.


● int length(Object  item)

 : item이 배열이나 컬렉션이면 요소의 개수를, 문자열이면 문자의 개수를 리턴 한다.

<c:set var="texts" value="${fn:split('Hi My name is waldo', ' ')}"/>

${fn:length(texts)} // 5

${fn:length("123456")} // 6


● String replace(String string, String before, String after)

 : string 내에 있는 before 문자열을 after 문자열로 모두 바꿔서 리턴 한다.

${fn:replace("hi hello", "hello", "hi")} // hi hi


// replace 함수는 HTML에서 공백과 줄바꿈을 표현할 때 사용할 수 있다.

${fn:replace("hell            o          o       ~", " ", "&nbsp;")} // hell            o          o       ~


<% pageContext.setAttribute("enter","\n"); %>

${fn:replace(info.text, enter, '<br/>') // 엔터처리


<% pageContext.setAttribute("enter","\n"); %>

${fn:replace(fn:replace(fn:escapeXml(info.content_txt), enter, '<br/>') , ' ', '&nbsp;')} // 엔터와 공백 처리


● String substring(String string, int begin, int end) : string에서 begin 인덱스에서 시작해서 end 인덱스에 끝나는 부분의 문자열을 리턴.

● String substringAfter(String string, String substring) : string에서 substring이 나타나는 이후의 부분에 있는 문자열을 리턴 한다.

● String substringBefore(String string, String substring) : string에서 substring이 나타나기 이전의 부분에 있는 문자열을 리턴 한다.

${fn:substring(text, 3, 19)} // My name is waldo

${fn:substringAfter(text, "Hi ")} // My name is waldo

${fn:substringBefore(text, "waldo")} // Hi My name is


● String toLowerCase(String string) : string을 모두 소문자로 바꿔 리턴한다.

● String toUpperCase(String string) : string을 모두 대문자로 바꿔 리턴한다.

<c:set var="text" value="Hi My name is waldo"/>

${fn:toLowerCase(text)} // hi my name is waldo

${fn:toUpperCase(text)} // HI MY NAME IS WALDO


● String trim(String string)

 : string 앞뒤의 공백을 모두 제거하여 리턴 한다. 

<c:set var="text" value="          blank spcae          "/>

${fn:length(text)}  // 31

<c:set var="text" value="${fn:trim(text)}"/>

${fn:length(text)}  // 11



출처 - http://noritersand.tistory.com/260


'Language > JSP' 카테고리의 다른 글

[URI] 한국어가 어떻게 URL에서 Percent-encoding 될까?  (0) 2019.09.11
JSTL 정리  (0) 2014.11.14
JSTL: fmt  (0) 2014.11.14
JSTL: core  (0) 2014.11.14
JSTL  (0) 2014.11.14
:

JSTL: fmt

Language/JSP 2014. 11. 14. 17:39

FMT, I18N - 국제화(Internationalization)

기능  : 지역, 메시지 형식, 숫자 및 날짜형식

접두어(Prefix)  :  fmt

directive : <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>


JSTL 국제화 지역화 태그로 다국어 문서를 처리할 때 유용하고, 날짜와 숫자 형식을 다룰 때 사용된다.  




목차

setLocale

requestEncoding

bundle

setBundle

message

formatNumber

parseNumber

formatDate

parseDate

setTimeZone, timeZone





setLocale

다국어를 지원하는 페이지를 만들 경우 ResourceBundle로 불러오는 *.properties 파일들과 연계되어서 사용한다. 


<fmt:setLocale value="locale"  [variant="variant"] [scope="{page|request|session|application}"]/>


 value의 locale 값은 http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt 언어코드와 http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html  국가코드로  이루어진다. 생략될경우 톰캣 서버의 기본 값으로 설정이 되고, 둘 중에 하나만 사용할 수도 있다.


 <%@ page contentType = "text/html; charset=utf-8" %> 

 <%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

 <%@ taglib  uri="http://java.sun.comjsp/jsp/jstl/fmt" prefix="fmt"%> 


 <pre> 

    default  locale  : <%=  response.getLocale() %> 

    set  locale  : ko <fmt:setLocale value="ko"  /> 

    now: <%=  response.getLocale() %> 

    set  locale  : ja  <fmt:setLocale value="ja"  /> 

    now: <%=  response.getLocale() %> 

    set  locale  : en  <fmt:setLocale value="en"  /> 

    now: <%=  response.getLocale() %> 

 </pre> 




requestEncoding

request.setCharacterEncoding() 역할을 한다. 


<fmt:requestEncoding  [value="charsetName"]/> 

 <%@ page contentType = "text/html;charset=utf-8" %> 

 <%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 


 <%@ taglib  uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> 

 <fmt:requestEncoding value="utf-8"/> 

 파라미터:<c:out value="${param.id}"/> 
 <form  method="post"> 
       <input type="text"  name="id"/> 
       <input type="submit"/> 

 </form> 



bundle
properties 확장자를 사용하는 자원 파일을 읽어오는 역할을 한다. 

<fmt:bundle  basename="basename"  [prefix="prefix"]> 
     body content 
</fmt:bundle> 

basename 속성에  지정된 properties 파일을  찾아서 locale  에  따라 읽어들인다.  
properties 파일은 보통 WEB-INF/classes 아래에 위치하며 디렉토리의 깊이에 따라서 패키지형식의 이름을 취한다. TestBundle.properties 파일이com/itexpert/test/msg 디렉토리에 있다면 basename="com.itexpert.test.msg.TestBundle"  이라고 지정하면 된다. 

locale이 ko라면 TestBundle_ko.properties 파일을 읽어오게 되며, locale이 맞지 않는 경우에는 TestBundle.properties처럼 코드가 붙지 않은 파일을 읽어온다.

prefix 속성은 key 명칭이 공통적인 부분을 지정해서 body에서 표현되는 key를 단축시킨다. import 에서 패키지 명을 지정하면 클래스명만 쓸 수 있는 것과 같이 생각할 수  있다.


setBundle
페이지 전체에서 사용할 수 있는 번들을 지정할 수 있는데, 이에 대한 지정은 <fmt:setBundle/> 태그가 담당한다. var속성에서 정한 변수를 이후에 나오는 <fmt:message/>태그에서 basename  속성에 변수 명으로 대체할 수  있다. 

<fmt:setBundle  basename="basename" [var="varName"] [scope="{page|request|session|application}"]/> 



message
 번들 태그에서 정한  값들을 가져온다. 

Syntax 1: body  없는 경우
<fmt:message  key="messageKey"  [bundle="resourceBundle"] [var="varName"] 
        [scope="{page|request|session|application}"]/> 

Syntax 2: 메시지 파라미터를 지정하는 body가 있는 경우
<fmt:message  key="messageKey"  [bundle="resourceBundle"] [var="varName"] 
        [scope="{page|request|session|application}"]> 
        <fmt:param>  서브태그 
</fmt:message> 

Syntax 3: 키와 선택적 메시지 파라미터를 지정하는 body가 있는 경우
<fmt:message  [bundle="resourceBundle"]  [var="varName"] 
        [scope="{page|request|session|application}"]> 
        key 
        선택적 <fmt:param>  서브태그 
</fmt:message> 

 번들에 있는 key값을 불러온다. bundle 속성으로 번들을 직접 설정할 수도 있고, <fmt:bundle/> 태그 사이에 중첩되어서 키 값만 받아서 출력할 수 있다. 

● 예제 
1) 웹  루트\WEB-INF\classes\bundle  경로에  다음의 properties 파일  두  개를  작성  한다. 
- testBundle_ko.properties 
  name=\ud558\ud558\ud558. 
  message=JSTL \uc7ac\ubbf8\uc788\ub2e4. 

- testBundle.properties 
  name=Han. 
  message=JSTL is fun. 

※ 참고 :  properties 파일은 한글은 입력할 수 없기 때문에 유니코드로 입력해야 하며 j2sdk의 /bin/native2ascii.exe 파일을 이용하여 한글을 유니코드 값을 확인 할 수 있다.  먼저 한글을 입력하고 엔터를 누르면 유니코드로 변환되어 출력한다. 

 properties  파일을  두  개  작성하는  이유는 로케일에  따라 영어 또는  한글로 출력할  수  있다.  영어로 출력하기 위해서는 익스플로러의 "인터넷 옵션-일반-언어"에서 한국어를 지우고 영어를 선택하면 영어로 출력 된다. 

2) JSP  파일  작성 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib  prefix="c"  uri="http://java.sun.comjsp/jsp/jstl/core" %>
<%@ taglib  prefix="fmt"  uri="http://java.sun.com/jsp/jstl/fmt"  %>
 
<html>
<head><title>JSTL fmt  예제 -  bundle  , message</title></head>
<body>
 
<fmt:bundle  basename="bundle.testBundle">
    <fmt:message  key="name"/>
    <p/>
    <fmt:message  key="message" var="msg"/>
    <c:out value="${msg}"/>
</fmt:bundle>
 
</body>
</html>



formatNumber
숫자  형식을 표현할  때 사용된다. 

Syntax 1: body 없는 경우
<fmt:formatNumber value="numericValue" 
        [type="{number|currency|percent}"]  [pattern="customPattern"] 

        [currencyCode="currencyCode"] [currencySymbol="currencySymbol"] 

        [groupingUsed="{true|false}"]  [maxIntegerDigits="maxIntegerDigits"] 

        [minIntegerDigits="minIntegerDigits"] [maxFractionDigits="maxFractionDigits"] 

        [minFractionDigits="minFractionDigits"]  [var="varName"] 

        [scope="{page|request|session|application}"]/> 


Syntax 2: 형식에 맞출 수치가 body에 있는 경우

<fmt:formatNumber  [type="{number|currency|percent}"] 

        [pattern="customPattern"]  [currencyCode="currencyCode"] 

        [currencySymbol="currencySymbol"]  [groupingUsed="{true|false}"] 

        [maxIntegerDigits="maxIntegerDigits"]  [minIntegerDigits="minIntegerDigits"] 

        [maxFractionDigits="maxFractionDigits"] [minFractionDigits="minFractionDigits"] 

        [var="varName"] [scope="{page|request|session|application}"]> 

        형식화될 수치 

</fmt:formatNumber> 

<fmt:formatNumber value="1700600"/> // 1,700,600

<fmt:formatNumber value="1700600" type="currency" groupingUsed="true"/> // ₩1,700,600

<fmt:formatNumber value="50" type="percent" groupingUsed="false"/> // 5000%

<fmt:formatNumber value="1670400" type="currency"  currencySymbol="&"/> // &1,670,400

<fmt:formatNumber value="999" minIntegerDigits="5" minFractionDigits="2"/> // 00,999.00


속성

동적

Type

설명

value

true

String 

또는 Number

  형식화될 수치

type

true

String

  숫자, 통화, 퍼센트  중  어느 것으로 표시할  지 지정

  {number|currency|percent}

pattern

true

String

  사용자가  지정한 형식 패턴.

currencyCode

true

String

  ISO 4217 통화 코드 (통화 형식일 때만 적용)

  (type="currency")

currencySymbol

true

String

  통화 기호 (통화 형식일 때만 적용)

  (type="currency")

groupingUsed

true

boolean

  형식 출력에 그룹 분리기호를 포함할지 여부

 (기본값은 true)

maxIntegerDigits

true

int

  형식 출력에서 integer 최대 자리 수

minIntegerDigits

true

int

  형식 출력에서 integer 최소 자리 수

maxFractionDigits

true

int

  형식 출력에서 소수점 이하 최대 자리 수

minFractionDigits

true

int

  형식 출력에서 소수점 이하 최소 자리 수

var

false

String

  형식 출력 결과 문자열을 담는 scope에 해당하는 변수명

scope

false

String

  var의 scope

  



parseNumber

반대로 정해진 패턴을 문자열에서 수치를 파싱해내는 태그


Syntax 1: body가  없는 경우

<fmt:parseNumber value="numericValue" 

        [type="{number|currency|percent}"]  [pattern="customPattern"] 

        [parseLocale="parseLocale"] [integerOnly="{true|false}"] 

        [var="varName"] [scope="{page|request|session|application}"]/> 


Syntax 2: 파싱할 수치를 body에 갖고 있는 경우

<fmt:parseNumber  [type="{number|currency|percent}"] 

        [pattern="customPattern"]  [parseLocale="parseLocale"] 

        [integerOnly="{true|false}"]  [var="varName"] 

        [scope="{page|request|session|application}"]> 

        파싱할 수치 

</fmt:parseNumber>


속성

동적

Type

설명

value

true

String 또는 Number

  파싱할 수치

 type

true

String

  숫자, 통화, 퍼센트 중 어느 것으로 표시할 지 지정

  {number|currency|percent}

pattern

true

String

  사용자가 지정한 형식 패턴

parseLocale

true

String 또는 java.util.Locale

  파싱 작업의 기본 형식 패턴(숫자, 통화, 퍼센트 각각)을 제공하는 Locale

integerOnly

true

boolean

  true일 경우 주어진 값에서 Integer 부분만 파싱

var

false

String

  파싱 결과(java.lang.Number)를 담는 scope에 해당하는 변수명

scope

false

String

  var의 scope



formatDate
날짜 형식을 표현하는 태그

<fmt:formatDate value="date" 
        [type="{time|date|both}"] [dateStyle="{default|short|medium|long|full}"] 
        [timeStyle="{default|short|medium|long|full}"] [pattern="customPattern"] 
        [timeZone="timeZone"] 
        [var="varName"] [scope="{page|request|session|application}"]/> 

속성

동적

Type

설명

value

true

java.util.Date

  형식화 될 Date와 Time 

type

true

String

  형식화 할 데이터가 시간, 날짜, 혹은 시간과 날짜인지 지정

dateStyle

true

String

  미리 정의된 날짜 형식. java.text.DateFormat 클래스에 정의된 문법을 따른다. 

  type 속성이 생략되었거나 date 혹은 body일 때 사용

timeStyle

true

String

  미리 정의된 시간 형식.

  type 속성이 time 혹은 body일 때 사용

pattern

true

String

  사용자 지정 형식 스타일

timeZone

true

String 또는 java.util.TimeZone

  형식화 시간에 나타날 타임 존

var

false

String

  형식 출력 결과 문자열을 담는 scope에 해당하는 변수명

scope

false

String

  var의 scope



parseDate
정해진 패턴의 문자열에서  날짜를 파싱해내는  태그 

Syntax 1: body 없는 경우
<fmt:parseDate value="dateString"
        [type="{time|date|both}"] [dateStyle="{default|short|medium|long|full}"] 
        [timeStyle="{default|short|medium|long|full}"] [pattern="customPattern"] 
        [timeZone="timeZone"] [parseLocale="parseLocale"] 
        [var="varName"] [scope="{page|request|session|application}"]/> 

Syntax 2: 파싱한 값이 body에 있는 경우
<fmt:parseDate  [type="{time|date|both}"] 
        [dateStyle="{default|short|medium|long|full}"]  
        [timeStyle="{default|short|medium|long|full}"] [pattern="customPattern"] 
        [timeZone="timeZone"] [parseLocale="parseLocale"] [var="varName"] 
        [scope="{page|request|session|application}"]> 
        파싱할 Date  와 time 
</fmt:parseDate> 

속성

동적

Type

설명

value

true

java.util.Date

  파싱할 Date와 Time 

type

true

String

  파싱할 데이터가 시간, 날짜, 혹은 시간과 날짜인지 지정

dateStyle

true

String

  미리 정의된 날짜 형식. java.text.DateFormat 클래스에 정의된 문법을 따른다.

  type 속성이 생략되었거나 date 혹은 body일 때 사용

timeStyle

true

String

  미리 정의된 시간 형식

  type 속성이 time 혹은 body일 때 사용

pattern

true

String

  사용자 지정 형식 스타일 

timeZone

true

String 또는 java.util.TimeZone

  형식화 시간에 나타날 타임 존 

parseLocale

true

String 또는 java.util.Locale

  파싱하는 동안 적용될 미리 정의된 형식스타일의 Locale 

var

false

String

  파싱 결과(java.util.Date)를 담는 scope에 해당하는 변수명 

scope

false

String

  var의 scope


● 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
    <pre>
        <fmt:setLocale value="ko_KR"/>
        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#"/>
 
        <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초"/>
    </pre>
</body>
</html>




setTimeZone, timeZone
<fmt:setTimeZone/> : 특정 스코프의 타임 존을 설정한다.
<fmt:setTimeZone value="timeZone" [var="varName"] [scope="{page|request|session|application}"]/>

<fmt:timeZone/> : 타임 존을 부분 적용한다.
<fmt:timeZone value="timeZone"> 
    body content 
</fmt:timeZone> 

● 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
 
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
    <pre>
        <fmt:setLocale value="ko_KR"/>
        <jsp:useBean id="now" class="java.util.Date"/>
 
        default : <c:out value="${now}"/>
        Korea KST :
        <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
         
        <fmt:timeZone value="GMT">
            Swiss GMT :
            <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
        </fmt:timeZone>
 
        <fmt:timeZone value="GMT-8">
            NewYork GMT-8 :
            <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
        </fmt:timeZone>
    </pre>
</body>
</html>




출처 - http://noritersand.tistory.com/256


'Language > JSP' 카테고리의 다른 글

JSTL 정리  (0) 2014.11.14
JSTL: fn  (0) 2014.11.14
JSTL: core  (0) 2014.11.14
JSTL  (0) 2014.11.14
JSP 게시판 구현 시 Paging 처리 하기  (0) 2014.11.11
:

JSTL: core

Language/JSP 2014. 11. 14. 17:38

CORE, 코어

기능  : 변수지원, 흐름제어, URL처리

접두어(Prefix)  :  c

directive : <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


EL 지원 기능 : catch, out, remove, set

흐름 제어 기능 : choose, forEach, forTokens, if

URL 관리기능 : import, param, redirect, param, url



목차

catch
choose, when, otherwise
forEach
forTokens
import
if
out
param
redirect
set, remove
url





catch

body 위치에서 실행되는 코드의 예외를 잡아내는 역할을 담당한다.

<c:catch  var="name">

     body  content

</c:catch>

<%@ page contentType = "text/html; charset=utf-8" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<h3>코어</h3>

<h4><c:out></h4>

<pre>

${1+2} <c:out value="${1+2}"/>

${1>3} <c:out value="${1>3}"/>

${1 gt 3} <c:out value="${1 gt 3}"/>


\$표시 <c:out value="${'${'}test}"/>


● escapeXml 속성 기본 값은  false

false:  <c:out value="<b>bold</b>  <,>,&,',\"  "  escapeXml="false"/>

true:   <c:out value="<b>bold</b>  <,>,&,',\"  "  escapeXml="true"/>


● " 큰따옴표 사용주의  ' 작은따옴표로 대치

<c:out  value='<font  color="blue">파랑</font>'/>

<c:out  value='<font  color="blue">파랑</font>'  escapeXml="false"/>


● 기타 예제

<hr><h4><c:set></h4>

set  session  scope  var  "name":  <c:set  var="name"  value="하늘"  scope="session"/>

c:out  name:  <c:out  value="${name}"/>

expression  name:  <%=  session.getAttribute("name")%>

set  page  scope  var  "name":  <c:set  var="name">

   hello

</c:set>

c:out  name:  <c:out  value="${pageScope.name}"/>

c:out  sessionScope.name:  <c:out  value="${sessionScope.name}"/>

expression  name:  <%=  session.getAttribute("name")%>

<hr><h4><c:remove></h4>

remove  session  scope  var  "name":  <c:remove  var="name"  scope="session"/>

expression  name:  <%=  session.getAttribute("name")%>

c:out  sessionScope.name:  <c:out  value="${sessionScope.name}"/>


<hr><h4><c:catch></h4>

<c:catch  var="errmsg">

line1

<%=1/0 %>

line2

</c:catch>

<c:out  value="${errmsg}"/>

</pre>




choose - when - otherwise

<c:choose/> 태그는 java의 switch 문과 같지만, 조건에 문자열 비교도 가능하고 쓰임의 범위가 넓다. 또한 <c:if/> 태그에 else가 없기 때문에 이의 대체 기능도 수행한다.

<c:choose>

     body  content 

     (하나 이상의  <when>과 하나 이하의  <otherwise> 서브태그)

       <c:when  test="조건_1">

           body  content

       </c:when>

       <c:when  test="조건_2">

           body  content

       </c:when>

          :

       <c:otherwise>

           conditional  block

       </c:otherwise>

   </c:choose>


● 조건을 판단하는 간단한 예

<%@  page  contentType  =  "text/html;  charset=utf-8" %>

<%@  taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>


<h3>조건</h3>

파라미터 없음:<c:out  value="${empty  param.name}"  />

<h4><c:if test=""></h4>

<c:if  test="${empty  param.name}">

<form>

이름을 적어주세요.<br/>

     <input  type="text"  name="name"/>  <input  type="submit"  value="확인"/>

</form>

</c:if>

<c:if  test="${!empty  param.name}">

    안녕하세요.  <c:out  value="${param.name}"/>님.

</c:if>


<h4><c:choose> <c:when  test="">  <c:otherwise></h4>

<c:choose>

     <c:when  test="${empty  param.name}">

         <form>

        이름을 적어주세요.<br/>

             <input  type="text"  name="name"/>   <input  type="submit"  value="확인"/>

         </form>

     </c:when>

     <c:when  test="${param.name=='admin'}">

        안녕하세요. 관리자님.

     </c:when>

     <c:otherwise>

        안녕하세요.  <c:out  value="${param.name}"/>님.

     </c:otherwise>

</c:choose>


● 기타 예제

<c:choose>

<c:when test="${param.num1%12==0}">

${param.num1 }은 3과 4의 배수<br/>

</c:when>

<c:when test="${param.num1%3==0}">

${param.num1 }은 3의 배수<br/>

</c:when>

<c:when test="${param.num1%4==0}">

${param.num1 }은 4의 배수<br/>

</c:when>

<c:otherwise>

${param.num1 }은 3또는 4의 배수가 아님<br/>

</c:otherwise>

</c:choose>



forEach

반복실행 태그

- Syntax 1 : 객체 전체에 걸쳐서 반복

   <c:forEach  [var="varName"]  items="collection"  [varStatus="varStatusName"]

            [begin="begin"]  [end="end"]  [step="step"]>

       body  content

   </c:forEach>


- Syntax 2 : 지정한 횟수만큼 반복

   <c:forEach  [var="varName"]  [varStatus="varStatusName"]

            begin="begin"  end="end"  [step="step"]>

       body  content

   </c:forEach>


<c:forEach/> 태그는 여러 가지로 활용이 가능하다. 원하는 구간만큼 반복할 수도 있고, 객체를 받아와서 그 객체의 길이만큼 반복할 수도 있다.  

begin, end 속성은 시작번호와 끝 번호를 지정하고, step 속성을 이용해서 증가 구간을 정할 수 있다.  var 속성에서 정한 변수로 반복되는 내부 구간에서 사용할 수 있다.


● begin - end

<table>

     <tr><td>Value</td>

       <td>Square</td></tr>

   <c:forEach  var="x"  begin="0"  end="10"  step="2">

     <tr><td><c:out  value="${x}"/></td>

         <td><c:out  value="${x  *  x}"/></td></tr>

   </c:forEach>

</table>


● 컬렉션의 멤버들 사이를 반복할 때 <c:forEach> 태그의 추가 애트리뷰트인 items 애트리뷰트가 사용된다.

<c:forEach var="dto" items="${list}">

이름:${dto.name}, 제목:${dto.subject}<br/>

</c:forEach>


● varStatus은 상태 값을 의미하며 다음의 값을 갖는다.

- current : 현재 아이템

- index : 0부터의 순서

- count : 1부터의 순서

- first : 현재 루프가 처음인지 반환

- last : 현재 루프가 마지막인지 반환

- begin : 시작값

- end : 끝값

- step : 증가값

<c:forEach items="${RESULT}" var="RESULT" varStatus="status"> 

       forEach의 현재 아이템은 : ${status.current}

</c:forEach>


● 기타 예제

<c:forEach var="n" begin="1" end="9">

${param.num}*${n}=${param.num*n}<br/>

</c:forEach>



<c:forEach var="dto" items="${list}">

이름:${dto.name},

제목:${dto.subject}<br/>

</c:forEach>



<c:forEach var="dto" items="${list}" varStatus="s">

이름:${dto.name},

제목:${dto.subject}<br/>

현재아이템:${s.current}<br/>

0부터의순서:${s.index}<br/>

1부터의순서:${s.count}<br/>

처음이냐?:${s.first}<br/>

마지막이냐?:${s.last}<br/>

</c:forEach>



<c:forEach var="dto" items="${lists}">

<dl>

<dd class="num">${dto.num}</dd>

<dd class="subject"><a href="">${dto.subject}</a></dd>

<dd class="name">${dto.name}</dd>

<dd class="created">${dto.created}</dd>

<dd class="hitCount">${dto.hitCount}</dd>

</dl>

</c:forEach>



forTokens

<c:forTokens/> 는  java.util.StringTokenizer 를 이용한 것이다

<c:forTokens items="stringOfTokens" delims="delimiters" 

     [var="varName"] [varStatus="varStatusName"]  [begin="begin"]  [end="end"]  [step="step"]>

     body  content

</c:forEach>

<%@  page  contentType  =  "text/html;  charset=utf-8" %>

<%@  taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>


<h3>반복</h3>

<h4><c:forEach></h4>


<c:forEach  var="one"  begin="1"  end="10">

     <c:out  value="${one}"/>

</c:forEach>

<p><b>header</b></p>

<c:forEach  var="h"  items="${header}">

     <c:out  value="${h.key}:${h.value}"/><br/>

</c:forEach>


<h4><c:forTokens></h4>

<c:forTokens  var="one"  items="서울|인천,대전,대구,부산,광주,평양"

             delims=","  varStatus="sts">

     <c:out  value="${sts.count}:${one}"/>·

</c:forTokens>

<hr/>


<c:forTokens  var="one" 

             items="서울|인천,대전,대구,부산,광주,평양"

             delims=",|"  varStatus="sts">

     <c:out  value="${sts.count}:${one}"/>•

</c:forTokens>



import

<c:import/> 는 아주 강력한 도구로 웹 어플리케이션 내부의 자원 접근은 물론이고, http, ftp 같은 외부에 있는 자원도 가져와서 페이지 내에 귀속시킨다. 자유롭게 가공할 수도 있고, 편집도 가능하다.

- Syntax 1 : 해당 주소를 바로 출력하거나 String 에 담아놓는다.

<c:import url="url" [context="context"]

         [var="varName"]  [scope="{page|request|session|application}"]

         [charEncoding="charEncoding"]>

    <c:param> 서브 태그 위치

</c:import>


- Syntax 2 : 해당 주소의 컨텐츠를  Reader 객체로

<c:import url="url" [context="context"]

         varReader="varReaderName"

         [charEncoding="charEncoding"]>

     varReader 를 사용하는 액션

</c:import>

<%@  page  contentType  =  "text/html;  charset=utf-8" %>

<%@  taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>


<c:set  var="url"  value="http://www.daum.net/"/>

<c:import  url="${url}"  var="u"/>

<c:out  value="${url}"/> 가져옵니다.

<hr/>

-- 홈페이지 결과 출력<br/>

  <c:out  value="${u}"  escapeXml="false"/>

<hr/>

<c:set  var="url"  value="http://www.naver.com"/>

<c:import  url="${url}"  var="u"/>

<c:out  value="${url}"/> 가져옵니다.

<hr/>

-- 소스 출력<br/>

<pre><c:out  value="${u}"/></pre>

<hr/>

<c:set  var="url"  value="gugu.jsp"/>

<c:import  url="${url}"  var="u">

     <c:param  name="su"  value="5"/>

</c:import>

<c:out  value="${url}"/> 가져옵니다.

<hr/>

<c:out  value="${u}"  escapeXml="false"/>

<hr/>



if

조건문을 사용할 때 쓴다.

- Syntax 1 : Body 없는 경우

<c:if test="testCondition" var="varName" [scope="{page|request|session|application}"]/>


- Syntax 2 : Body 있는 경우

<c:if test="testCondition" [var="varName"] [scope="{page|request|session|application}"]>

    body content

</c:if>

<form method="post">

수: <input type="text" name="num">

<input type="submit" value="결과">

</form>

//액션이 없어서 자기 자신에게 parameter를 전송하는 폼


<c:if test="${not empty param.num }">

<c:if test="${param.num % 2 == 0}">

${param.num}은 짝수<br/>

</c:if>

<c:if test="${param.num % 2 != 0 }">

${param.num}은 홀수<br/>

</c:if>

</c:if>



<c:if test="${dataCount==0}">

등록된게시물이음슴

</c:if>


<c:if test="${dataCount!=0}">

${pageIndexList}

</c:if>


  <c:if/> 에서 나온 결과를  varName 변수에 넣고, 나중에 활용이 가능하다. 

  변수의 scope는 임의로 지정할 수 있고, 생략될 경우 기본 값은  page 이며 else 문은 존재 하지 않는다.



● 자바스크립트 제어 

// 자바스크립트가 특정조건에 외부노출되는 것을 막음

<c:if test="${sessionScope.session.userId == dto.userId}">

    function updateBoard(boardNum)

    {

     var url = "<%=cp%>/board/update.action"

    

     location.href = url;

    }

</c:if>



out

JSP의 표현식을 대체하는 것으로 가장 많이 사용된다.

- Syntax 1 : body 없는 경우

<c:out value="value" [escapeXml="{true|false}"] [default="기본_값"]  />


- Syntax 2 : body 있는 경우

<c:out value="value" [escapeXml="{true|false}"]  />

     기본_값

</c:out>

  Hello  <c:out  value="${user.username}"  default="Guest"/>!


   <c:out  value="${user.company}"  escapeXml="false"/>


   <c:set  var="timezone"  scope="session">

      <c:out  value="${cookie['tzPref'].value}"  default="CST"/>

   </c:set>


 escapeXml 애트리뷰트 또한 선택사항이다.  

"<",  ">",  "&" 같은 캐릭터가  <c:out> 태그에 의해 아웃풋 될 때 종료되는지의 여부를 제어한다.  

escapeXml이  true로 설정되어 있다면 이 캐릭터들은 상응하는  XML 인터티(<,  >,  &)로 바뀐다.(escapeXml 기본값  true)

 


param

보통 import, redirect, url 태그와 같이 쓰이는 태그. "파라미터=값" 형식을 표현한다.

<c:param 속성="값".../>

<c:import  url="/exec/doIt">

   <c:param  name="action"  value="register"/>

</c:import>


// 이 방법은 아래 태그와 같은 효과가 있다 :

<c:import  url="/exec/doIt?action=register"/>



redirect

response.sendRedirect()를 대체하는 태그. 컨텍스트를 지정해서 다른 컨텍스트로 이동이 가능하다.

- Syntax 1 :  Body 없는 경우

<c:redirect url="value" [context="context"]/>


- Syntax 2 :  Body 있는 경우 쿼리 스트링 파라미터 지정

<c:redirect url="value" [context="context"]/>

    <c:param> 서브태그

</c:redirect>

<%  response.setContentType("text/html"); %>

<%@  taglib  uri="http://java.sun.com/jstl/core"  prefix="c"%>


<c:redirect url="/test.jsp"/>



set, remove

set는 JSP의 setAttribute()와 같은 역할을  한다.  (page|request|session|application) 범위의 변수(속성)를 설정한다.

remove는 JSP의 removeAttribute()와 같은 역할을 한다.  (page|request|session|application) 범위의 변수(속성)를 제거한다. 


- Syntax 1 : scope 에 해당하는 변수에 속성 값을 정한다.

<c:set value="value" var="varName" [scope="{page|request|session|application}"]/>


- Syntax 2 : scope 에 해당하는 변수에  body 값을 정한다.

<c:set var="varName" [scope="{page|request|session|application}"]>

       body  content

</c:set>


- Syntax 3 : 속성 값으로  target 객체의 프로퍼티 값을 정한다.

<c:set value="value" target="target" property="propertyName"/>


- Syntax 4 : body 값으로  target 객체의 프로퍼티 값을 정한다.

<c:set target="target" property="propertyName">

      body  content

</c:set>


※ scope 속성이 생략될 경우 기본 값은 page다.

※ var와 target은 동시에 사용할 수 없다.


<c:set var="testObject" value="hello world!"/> // request.setAttribute("testObject", "hello world!")

<c:out value="${testObject}"/> // request.getAttribute("testObject")

var속성의 경우는 비교적 간단하다. 


<jsp:useBean id="map" class="java.util.HashMap"/>

<c:set target="${map}" property="hi" value="hello world!"/> // map.put("hi", "hello world!")

<c:out value="${map.hi}"/> // map.get("hi")


<jsp:useBean id="vo" class="com.test.TestVO"/>

<c:set target="${vo}" property="name" value="who?"/> // vo.setName("who?")

<c:out value="${vo.name}"/> // vo.getName()


<c:forEach items="${sampleList}" var="list">

<c:set target="${list}" property="col1" value="1234"/> // sampleList.get(loop).setCol1("1234")

<tr>

<td>${list.col1}</td> // sampleList.get(loop).getCol1()

<td>${list.col2}</td>

<td>${list.col3}</td>

<td>${list.col4}</td>

<td>${list.col5}</td>

<td>${list.col6}</td>

</tr>

</c:forEach>

target속성은 jsp에서 객체 생성 후 사용하거나 기존 객체의 getter/setter를 이용하는 방식이다.

 


url

<c:url/> 태그는 컨텍스트를 자동으로 추가해서 주소를 자동으로 생성해준다.  context 속성이 지정되었을 경우 value와 context 의 값은 /로 시작을 해야  된다. context 속성이 생략되면 당연히 현재의 컨텍스트가 적용된다.

- Syntax 1 : Body 없는 경우

<c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"]/>


- Syntax 2 : Body 있는 경우 파라미터 지정

<c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"]>

     <c:param> 서브태그

</c:url>

<%  response.setContentType("text/html"); %>

<%@  taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>


<c:url  value="/images/tomcat.gif"/>

<img  src='<c:url  value="/images/tomcat.gif"/>'  />




출처 - http://noritersand.tistory.com/113

'Language > JSP' 카테고리의 다른 글

JSTL: fn  (0) 2014.11.14
JSTL: fmt  (0) 2014.11.14
JSTL  (0) 2014.11.14
JSP 게시판 구현 시 Paging 처리 하기  (0) 2014.11.11
JSP 내장 기본 객체의 영역(scope)  (0) 2014.11.11
:

JSTL

Language/JSP 2014. 11. 14. 17:38

JSTL, JSP Standard Tag Library



개요

 JSP는 XML처럼 사용자가 태그를 정의해 사용하는 것이 가능하며 이런 태그를 사용자 정의 태그라 하는데 이들 중 자주 사용하는 것을 표준으로 만들어 놓은것이 JSTL이다. JSTL은 일반적인 웹 애플리케이션 기능인 반복과 조건, 데이터관리, 포맷, XML조작, 데이터베이스 엑세스를 구현하는 라이브러리를 제공하고 있다.


<접두어:태그명 속성1:값1, 속성:값2, ...>

Body 없는 경우 :

<c:if test="testCondition" var="varName"  [scope="{page|request|session|application}"]/>


Body 있는 경우 :

<c:if test="testCondition"  [var="varName"]  

[scope="{page|request|session|application}"]>

      blah blah blah

</c:if>


작성 시 주의사항은 액션태그가 그렇듯 XML기반에서 작성되었기 때문에 모든 태그는 시작태그과 종료태그를 쌍으로 작성해야한다.


 JSTL은 태생이 커스텀태그이기 때문에 jsp와 밀접하게 관계가 있다. application, session, request, response,  pageContext 등의 내장객체에 쉽게 접근하며, 그 외에도 파라미터, 헤더, 쿠키 등을 복잡한 코드를 사용하지 않고, 쉽게 직관적으로 사용할 수 있다. 또한 기본적인 연산이나 객체의 비교 등

을  .equals() 메소드 등을 이용하는 대신  == 와 같이 쉽게 구현했으며, 조건, 반복, 이동에 대한 태그를 지원하기 때문에 태그만으로도 반복 기능을 구현할 수 있다.



태그의 종류

- 코어(Core)

⋅기능  : 변수지원, 흐름제어, URL처리

⋅접두어(Prefix)  :  c

⋅URI  :  http://java.sun.com/jsp/jstl/core


- XML

⋅기능  :  XML 코어, 흐름 제어,  XML 변환

⋅접두어(Prefix)  :  x


- 국제화

⋅기능  : 지역, 메시지 형식, 숫자 및 날짜형식

⋅접두어(Prefix)  :  fmt


- 데이터베이스

⋅기능  :  SQL

⋅접두어(Prefix)  :  sql


- 함수(Functions)

⋅기능  : 컬렉션 처리,  String 처리

⋅접두어(Prefix)  :  fn



환경설정

1) 라이브러리

 기존의 컨텍스트에서 JSTL을 사용하려면 웹 어플리케이이션의 WEB-INF/lib 디렉토리에 필요한 라이브러리를 복사한다.

JSTL의 주된 라이브러리 파일은 jstl.jar, standard.jar이고, XML에서 지원되는 기능을 사용하려면 jaxen-full.jar, saxpath.jar, jaxp-api.jar 파일 등이 필요하다.


http://tomcat.apache.org/taglibs/standard/

http://blog.naver.com/PostView.nhn?blogId=topgunmagic&logNo=120174261098


혹은 톰캣설치폴더\webapps\examples\WEB-INF\lib 에서 가져온다.



1.2 버전은 톰캣 6.0부터, 1.1버전은 톰캣 5.5부터 사용가능


2) JSP에 디렉티브 taglib 추가

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml"%>

<%@ taglib prefix="fmt  uri="http://java.sun.com/jsp/jstl/fmt"%>

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>



출처 - http://noritersand.tistory.com/122


'Language > JSP' 카테고리의 다른 글

JSTL: fmt  (0) 2014.11.14
JSTL: core  (0) 2014.11.14
JSP 게시판 구현 시 Paging 처리 하기  (0) 2014.11.11
JSP 내장 기본 객체의 영역(scope)  (0) 2014.11.11
exception 내장 객체  (0) 2014.11.11
:

JSP 게시판 구현 시 Paging 처리 하기

Language/JSP 2014. 11. 11. 14:27

서버에서 Paging 에 대한 로직 처리 후, jsp include, param 기능을 사용하여 구현 한다.


1. Paging

Paging 기능을 구현하는 VO Class 이다. setTotalCount(int totalCount) 호출 시 makePaging() 함수 호출 한다.


/**
 * Paging
 *
 * @author whitelife
 * @since 2014.10.05
 * @version 0.1
 */
public class Paging {
    private int pageSize; // 게시 글 수
    private int firstPageNo; // 첫 번째 페이지 번호
    private int prevPageNo; // 이전 페이지 번호
    private int startPageNo; // 시작 페이지 (페이징 네비 기준)
    private int pageNo; // 페이지 번호
    private int endPageNo; // 끝 페이지 (페이징 네비 기준)
    private int nextPageNo; // 다음 페이지 번호
    private int finalPageNo; // 마지막 페이지 번호
    private int totalCount; // 게시 글 전체 수

    /**
     * @return the pageSize
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * @param pageSize the pageSize to set
     */
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * @return the firstPageNo
     */
    public int getFirstPageNo() {
        return firstPageNo;
    }

    /**
     * @param firstPageNo the firstPageNo to set
     */
    public void setFirstPageNo(int firstPageNo) {
        this.firstPageNo = firstPageNo;
    }

    /**
     * @return the prevPageNo
     */
    public int getPrevPageNo() {
        return prevPageNo;
    }

    /**
     * @param prevPageNo the prevPageNo to set
     */
    public void setPrevPageNo(int prevPageNo) {
        this.prevPageNo = prevPageNo;
    }

    /**
     * @return the startPageNo
     */
    public int getStartPageNo() {
        return startPageNo;
    }

    /**
     * @param startPageNo the startPageNo to set
     */
    public void setStartPageNo(int startPageNo) {
        this.startPageNo = startPageNo;
    }

    /**
     * @return the pageNo
     */
    public int getPageNo() {
        return pageNo;
    }

    /**
     * @param pageNo the pageNo to set
     */
    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    /**
     * @return the endPageNo
     */
    public int getEndPageNo() {
        return endPageNo;
    }

    /**
     * @param endPageNo the endPageNo to set
     */
    public void setEndPageNo(int endPageNo) {
        this.endPageNo = endPageNo;
    }

    /**
     * @return the nextPageNo
     */
    public int getNextPageNo() {
        return nextPageNo;
    }

    /**
     * @param nextPageNo the nextPageNo to set
     */
    public void setNextPageNo(int nextPageNo) {
        this.nextPageNo = nextPageNo;
    }

    /**
     * @return the finalPageNo
     */
    public int getFinalPageNo() {
        return finalPageNo;
    }

    /**
     * @param finalPageNo the finalPageNo to set
     */
    public void setFinalPageNo(int finalPageNo) {
        this.finalPageNo = finalPageNo;
    }

    /**
     * @return the totalCount
     */
    public int getTotalCount() {
        return totalCount;
    }

    /**
     * @param totalCount the totalCount to set
     */
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
        this.makePaging();
    }

    /**
     * 페이징 생성
     */
    private void makePaging() {
        if (this.totalCount == 0) return; // 게시 글 전체 수가 없는 경우
        if (this.pageNo == 0) this.setPageNo(1); // 기본 값 설정
        if (this.pageSize == 0) this.setPageSize(10); // 기본 값 설정

        int finalPage = (totalCount + (pageSize - 1)) / pageSize; // 마지막 페이지
        if (this.pageNo > finalPage) this.setPageNo(finalPage); // 기본 값 설정

        if (this.pageNo < 0 || this.pageNo > finalPage) this.pageNo = 1; // 현재 페이지 유효성 체크

        boolean isNowFirst = pageNo == 1 ? true : false; // 시작 페이지 (전체)
        boolean isNowFinal = pageNo == finalPage ? true : false; // 마지막 페이지 (전체)

        int startPage = ((pageNo - 1) / 10) * 10 + 1; // 시작 페이지 (페이징 네비 기준)
        int endPage = startPage + 10 - 1; // 끝 페이지 (페이징 네비 기준)

        if (endPage > finalPage) { // [마지막 페이지 (페이징 네비 기준) > 마지막 페이지] 보다 큰 경우
            endPage = finalPage;
        }

        this.setFirstPageNo(1); // 첫 번째 페이지 번호

        if (isNowFirst) {
            this.setPrevPageNo(1); // 이전 페이지 번호
        } else {
            this.setPrevPageNo(((pageNo - 1) < 1 ? 1 : (pageNo - 1))); // 이전 페이지 번호
        }

        this.setStartPageNo(startPage); // 시작 페이지 (페이징 네비 기준)
        this.setEndPageNo(endPage); // 끝 페이지 (페이징 네비 기준)

        if (isNowFinal) {
            this.setNextPageNo(finalPage); // 다음 페이지 번호
        } else {
            this.setNextPageNo(((pageNo + 1) > finalPage ? finalPage : (pageNo + 1))); // 다음 페이지 번호
        }

        this.setFinalPageNo(finalPage); // 마지막 페이지 번호
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}


2. Controller

setTotalCount(totalCount) 를 호출 한다. CustomServlet 으로 처리도 가능 하다.


/**
 * 리스트 조회
 *
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value="/list", method=RequestMethod.GET)
public ModelAndView list(Sample sample) throws Exception {
    try {
        // (Before) Doing...

        Paging paging = new Paging();
        paging.setPageNo(1);
        paging.setPageSize(10);
        paging.setTotalCount(totalCount);


        // (After) Doing...
    } catch (Exception e) {
        throw e;
    }
}


3. paging.jsp

View 스타일에 따라 수정이 가능 하다.


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<div class="paginate">
    <a href="javascript:goPage(${param.firstPageNo})" class="first">처음 페이지</a>
    <a href="javascript:goPage(${param.prevPageNo})" class="prev">이전 페이지</a>
    <span>
        <c:forEach var="i" begin="${param.startPageNo}" end="${param.endPageNo}" step="1">
            <c:choose>
                <c:when test="${i eq param.pageNo}"><a href="javascript:goPage(${i})" class="choice">${i}</a></c:when>
                <c:otherwise><a href="javascript:goPage(${i})">${i}</a></c:otherwise>
            </c:choose>
        </c:forEach>
    </span>
    <a href="javascript:goPage(${param.nextPageNo})" class="next">다음 페이지</a>
    <a href="javascript:goPage(${param.finalPageNo})" class="last">마지막 페이지</a>
</div>


4. list.jsp

paging.jsp 를 호출 하는 부분이다.


// (Before) Doing...
<jsp:include page="paging.jsp" flush="true">
    <jsp:param name="firstPageNo" value="${paging.firstPageNo}" />
    <jsp:param name="prevPageNo" value="${paging.prevPageNo}" />
    <jsp:param name="startPageNo" value="${paging.startPageNo}" />
    <jsp:param name="pageNo" value="${paging.pageNo}" />
    <jsp:param name="endPageNo" value="${paging.endPageNo}" />
    <jsp:param name="nextPageNo" value="${paging.nextPageNo}" />
    <jsp:param name="finalPageNo" value="${paging.finalPageNo}" />
</jsp:include>
// (After) Doing...


출처 - http://blog.whitelife.co.kr/215


'Language > JSP' 카테고리의 다른 글

JSTL: core  (0) 2014.11.14
JSTL  (0) 2014.11.14
JSP 내장 기본 객체의 영역(scope)  (0) 2014.11.11
exception 내장 객체  (0) 2014.11.11
page 기본 객체  (0) 2014.11.11
:

JSP 내장 기본 객체의 영역(scope)

Language/JSP 2014. 11. 11. 14:17

- 웹 어플리케이션은 page, request, session, applicaition 이라는 4개의 영역을 가지고 있다.


- 기본 객체의 영역은 객체의 유효기간이라고도 불리며, 객체를 누구와 공유할 것인가를 나타낸다.


(1) page 영역


- page 영역은 한 번의 웹 브라우저(클라이언트)의 요청에 대해 하나의 JSP 페이지가 호출된다.


- 웹 브라우저의 요청이 들어오면 이때 단 한 개의 페이지만 대응이 된다.


- 따라서 page 영역은 객체를 하나의 페이지 내에서만 공유한다.


- page 영역은 pageContext 기본 객체를 사용한다.



(2) request 영역


- request 영역은 한 번의 웹 브라우저(클라이언트)의 요청에 대해 같은 요청을 공유하는 페이지가 대응된다. 


- 이것은 웹 브라우저의 한 번의 요청에 단지 한 개의 페이지만 요청될 수 있고, 때에 따라 같은 request 영역이면 두 개의 페이지가 같은 요청을 공유할 수 있다.


- 따라서 request 영역은 객체를 하나 또는 두 개의 페이지 내에서 공유할 수 있다.


- include 액션 태그, forward 액션 태그를 사용하면 request 기본 객체를 공유하게 되어서 같은 reqeust 영역이 된다.


- 주로 페이지 모듈화에 사용된다.



(3) session 영역


- session 영역은 하나의 웹 브라우저 당 1개의 session 객체가 생성된다.


- 즉, 같은 웹 브라우저 내에서는 요청되는 페이지들은 같은 객체를 공유학 ㅔ된다.



(4) application 영역


- application 영역은 하나의 웹 어플리케이션 당 1개의 applicaition 객체가 생성된다.


- 즉, 같은 웹 어플리케이션에 요청되는 페이지들은 같은 객체를 공유한다.


출처 - http://hyeonstorage.tistory.com/88

'Language > JSP' 카테고리의 다른 글

JSTL  (0) 2014.11.14
JSP 게시판 구현 시 Paging 처리 하기  (0) 2014.11.11
exception 내장 객체  (0) 2014.11.11
page 기본 객체  (0) 2014.11.11
config 내장 객체  (0) 2014.11.11
:

exception 내장 객체

Language/JSP 2014. 11. 11. 14:16

- exception 내장 객체는 JSP 페이지에서 예외가 발생하였을 경우 예외를 처리할 페이지를 지정하였을 때 예외 페이지에 전달되는 객체이다.


- exception 객체는 page 디렉티브의 isErrorPage 속성을 true 로 지정한 JSP 페이지에서만 사용 가능한 내장 객체다


- java.lang.Throwable 객체 타입이다.


- exception 내장 객체의 메소드


 메소드

설명 

String getMessage() 

발생된 예외의 메시지를 리턴한다. 

String toString() 

발생된 예외 클래스명과 메시지를 리턴한다. 

String pritnStackTrace() 

발생된 예외를 역추적하기 위해 표준 예외 스트림을 출력한다. 예외 발생시 예외가 발생한 곳을 알아낼 때 주로 사용된다. 


출처 - http://hyeonstorage.tistory.com/87

'Language > JSP' 카테고리의 다른 글

JSP 게시판 구현 시 Paging 처리 하기  (0) 2014.11.11
JSP 내장 기본 객체의 영역(scope)  (0) 2014.11.11
page 기본 객체  (0) 2014.11.11
config 내장 객체  (0) 2014.11.11
application 기본 객체  (0) 2014.11.11
:

page 기본 객체

Language/JSP 2014. 11. 11. 14:16

- page 내부 객체는 JSP 페이지 그 자체를 나타내는 객체이다.


- JSP 페이지 내에서 page 객체는 this 키워드(this : 자바에서 자기 자신을 가리키는 레퍼런스)로 자기 자신을 참조할 수가 있다.


- page 객체는 javax.servlet.jsp.HttpJspPage 객체 타입으로 JSP 내장 객체이다.


- 웹 컨테이너는 자바만을 스크립트 언어로 지원하기 때문에 page 객체는 현재 거의 사용되지 않는 내부 객체이다.


- 그러나 자바 이외의 다른 언어가 사용될 수 있도록 허용된다면, page 객체를 참조하는 경우가 발생할 수 있다.


출처 - http://hyeonstorage.tistory.com/86

'Language > JSP' 카테고리의 다른 글

JSP 내장 기본 객체의 영역(scope)  (0) 2014.11.11
exception 내장 객체  (0) 2014.11.11
config 내장 객체  (0) 2014.11.11
application 기본 객체  (0) 2014.11.11
session 내장 객체  (0) 2014.11.11
: