2010년 8월 19일 목요일

블로그 이전 했습니다.

텍스트 큐브에서 티스토리로 이전했습니다.

 

주소는

 

http://rooya85.tistory.com/

 

입니다.!

 

많은 관심 가져주세요~

2010년 8월 16일 월요일

@PathVariable 어노테이션을 이용한 URI 템플릿

RESTful 서비스가 유행하면서 URI를 다음과 같이 REST 방식으로 구성하는 경우가 있다.

 

 

기존에는 http://somehost/users/userinfo?id=madvirus 와 같이 파라미터를 이용해서 아이디나 이름을 전달받았다면, 이제는 URI에 아이디나 이름 등이 포함되도록 URL을 구성하고 있다.

 

스프링 3 버전에 추가된 기능 중 필자가 가장 반기는 기능 중의 하나가 URI 템플릿이며, 이 URI 템플릿을 이용하면 REST 방식의 URL 매칭을 쉽게 처리할 수 있다. URI 템플릿을 사용하는 방법은 매우 간단하며, 다음과 같이 두가지만 추가로 작업해주면 된다.

 

1. dispatcherServlet.xml 가장 밑에 다음을 추가한다.

 

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
  <property name="alwaysUseFullPath" value="true"/>
 </bean>
 
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="alwaysUseFullPath" value="true"/>
 </bean>

 

2. web.xml 에 다음을 추가한다.

 

  <servlet-mapping>
   <servlet-name>dispatcher</servlet-name>
   <url-pattern>*.nar</url-pattern> // 적절한 이름을 사용한다.
   <url-pattern>/board/*</url-pattern>  // 적절한 이름을 사용한다. 

  </servlet-mapping>

 

3. 해당 Controller에 다음과 같은 변수를 사용한다.

 

@RequestMapping 어노테이션의 값으로 {템플릿 변수}를 사용한다.

@PathVariable 어노테이션을 이용해서 {템플릿 변수}와 동일한 이름을 갖는 파라미터를 추가한다.

 

실제 URI 템플릿이 적용된 코드는 다음과 같다. (수정 중)

 

스프링3.0의 세가지 Layer

Presentation Layer(Spring MVC, DispatcherServlet)

 

Business Layer - Service, Spring Container(Service Bean, DAO Bean 등의 DI 관계)

 

Data Layer

 

PL <-- Controller --> BL <-- DAO --> DL

 

 

2010년 8월 7일 토요일

Oracle 사용자(회원) 비밀번호 암호화 하기

ex) getMD5("1234") = 81dc9bdb52d04dc20036dbd8313ed055

 

 /**
  * Turns array of bytes into string representing each byte as
  * a two digit unsigned hex number.
  * @param hash Array of bytes to convert to hex-string
  * @return  Generated hex string
  */
 private static String toHex(byte hash[]){
  StringBuffer buf = new StringBuffer(hash.length * 2);
  for (int i=0; i   int intVal = hash[i] & 0xff;
   if (intVal < 0x10){
    // append a zero before a one digit hex
    // number to make it two digits.
    buf.append("0");
   }
   buf.append(Integer.toHexString(intVal));
  }
  return buf.toString();
 }
 
 /**
  * Gets the MD5 hash of the given byte array.
  * @param b byte array for which an MD5 hash is desired.
  * @return 32-character hex representation the data's MD5 hash.
  */
 public static String getMD5String(byte[] b){
  String javaPackageMD5="";
  try{
   byte[] javaDigest = MessageDigest.getInstance("MD5").digest(b);
   javaPackageMD5 = toHex(javaDigest);
  }catch(Exception ex){
  }
  return javaPackageMD5;
 }
 
 /**
  * 단방향 암호화 처리(String)
  * @param str
  * @return
  */
 public static String getMD5(String str) {
  byte[] byteString = str.getBytes();
  return getMD5String(byteString);
 }

2010년 8월 3일 화요일

IBatis Framework

 

실행절차

  • 객체를 파라미터로 전달
    • JavaBeans, Map or primitive wrapper
  • 매핑되는 SQL문장을 수행
    • SQL Maps 프레임워크는 PreparedStatment 인스턴스 생성
    • 객체로부터 제공되는 값들을 파라미터로 설정
  • SQL 문장을 수행하고 ResultSet으로부터 결과 객체를 생성.
    • Update의 경우에는 영향을 받은 rows 수가 반환
    • 쿼리의 경우 하나 혹은 여러 객체들이 반환

 


iBatis관련 파일구성

  • SQL Map Configuration XML 파일
    • 설정 관련 정보 제공
  • SQL Map XML 파일
    • SQL 문장들을 제공
  • ibatis 라이브러리
    • 런타임 엔진 제공

 

 


 

slqmap 위치설정(sqlmap-config.xml)

  • src 의 config 안에 sql-map. xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" 
		"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
 
<sqlMapConfig>
	<!--cacheMap namespace="GlobalCache"> //new definition
     <cacheModel id="cache" readOnly="true" serialize="true" type="LRU">
         <flushOnExecute statement="insert*"/>
         <flushOnExecute statement="update*"/>
         <flushOnExecute statement="delete*"/>
         <property name="size" value="100000"/>
         <flushInterval hours="24"/>
     </cacheModel>  
	</cacheMap-->
 
	<!--settings cacheModelsEnabled="true" /-->
	<settings cacheModelsEnabled="true" enhancementEnabled="true"
		lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"
		maxTransactions="5" useStatementNamespaces="false"/>
	
	//Dao의 xml을 등록.
	<!-- ==========Framework Configuration Section============= -->
	<sqlMap resource="com/daewoobrenic/com/menu/dao/sqlmap/Menu.xml"/>
	<sqlMap resource="com/daewoobrenic/com/program/dao/sqlmap/Program.xml"/>
	<sqlMap resource="com/daewoobrenic/com/menu/authority/dao/sqlmap/Auth.xml"/>
	<sqlMap resource="com/daewoobrenic/com/user/dao/sqlmap/User.xml"/>
	<sqlMap resource="com/daewoobrenic/com/code/dao/sqlmap/Code.xml"/>
	<sqlMap resource="com/daewoobrenic/com/term/dao/sqlmap/Term.xml"/>
	
</sqlMapConfig>
 

 

SQL Map XML 파일

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Program">
 
			
	<typeAlias alias="program" type="com.daewoobrenic.com.program.model.Program"/>
 
	<resultMap id="program-resultMap" class="program" >
		<result property="id" column="program_id"/>
		<result property="name" column="program_name"/>
		<result property="path" column="program_path"/>
		<result property="desc" column="program_desc"/>
		<result property="div" column="div_code"/>
		<result property="scrtgrad" column="scrtgrad_code"/>
	</resultMap>	
<statement id="insertProgram" parameterClass="program" >
		INSERT INTO
		PROGRAM( program_id, program_name, program_path, program_desc, div_code, scrtgrad_code, first_insert_time, last_update_time )
		VALUES( #id#, #name#, #path#, #desc#, #div#, #scrtgrad#, SYSTIMESTAMP, SYSTIMESTAMP )
	</statement>
	  	
	<statement id="selectProgram" parameterClass="string" resultMap="program-resultMap" cacheModel="program-cache">
		SELECT program_id, program_name, program_path, program_desc, div_code, scrtgrad_code FROM PROGRAM
		WHERE program_id = #id#
	</statement>
	 
	<statement id="selectProgramList" parameterClass="program" resultMap="program-resultMap" cacheModel="program-cache">
		SELECT  program_id, program_name, program_path, program_desc, div_code, scrtgrad_code FROM PROGRAM
		ORDER BY program_id
	</statement>
	 
	<statement id="updateProgram" parameterClass="program">
		UPDATE PROGRAM SET
			program_id 			= #id#,
			program_name		= #name#,
			program_path		= #path#,
			program_desc		= #desc#,
			div_code            = #div#,
			scrtgrad_code       = #scrtgrad#,
			last_update_time	= SYSTIMESTAMP
		WHERE program_id = #id#
	</statement>
					
	<statement id="deleteProgram" parameterClass="string">
		DELETE FROM PROGRAM WHERE program_id = #id#
	</statement>
	</statement>
</sqlMap>
  • namespace
  • typeAlias - SQL maping을 할 model의 이름
  • resultMap
    • Query 컬럼명과 result 클래스의 property가 동일 할 경우에 ResultMap 생략 가능
    • class
      • resultMap 의 class 유형
      • JavaBean과 java.util.Map 모두 사용 가능
      • JavaBean 일 때
        • Query 조회결과 Row별로 JavaBean을 생성
        • Result element 속성에 Column 값을 저장
      • java.util.HashMap일때
        • Query 조회결과 Row별로 HashMap 생성
        • Result element의 id를 Key, Column 값을 Value로 HashMap에 저장
    • property : model
    • program_id : db의 column
    • ParameterClass, ParameterMap - db에 데이터가 들어갈 때
    • resultMap,resultClass- db에서 데이터를 꺼내올때
    • 여기서 #id# 는 id를 resultMap에서 정한 db에 컬럼에 맞는 값으로 binding 한다는 의미
  • ParameterMap
    •  ?를 사용하여 순서대로 바인딩
<parameterMap id="insert-product-param" class="com.domain.Product">
  <parameter property="id"/>
  <parameter property="description"/>
</parameterMap>
<statement id="insertProduct" parameterMap="insert-product-param">
  insert into PRODUCT (PRD_ID, PRD_DESCRIPTION) values (?,?);
</statement>
 

 
 

<![CDATA[ …. ]]>의 사용법

<statement id="getPersonsByAge" parameterClass="int" resultClass="examples.domain.Person">
<![CDATA[
  SELECT *
  FROM PERSON
  WHERE AGE > #value#
]]>
</statement>
 

 

cache 사용법

  • cacheModel
<cacheModel id="product-cache" imlementation="LRU">
  <flushInterval hours="24"/>
  <flushOnExecute statement="insertProduct"/>
  <flushOnExecute statement="updateProduct"/>
  <flushOnExecute statement="deleteProduct"/>
  <property name="size" value="1000" />
</cacheModel>
<statement id="getProductList" parameterClass="int" cacheModel="product-cache">
	select * from PRODUCT where PRD_CAT_ID = #value#
</statement>
  • Statement의 where조건을 기준으로 데이터 cache
    • imlementation: cache-types
      • memory : MEMORY cache는 reference type 을 이용하여 cache behavior 를 관리한다. 즉 garbage collector가 효출적으로 cache내에서의 저장여부를 결정한다.
      • LRU :Least Recently Used algorithm
      • FIFO : First In First Out algorithm
      • OSCACHE : OSCaching framework
    • 매 24시간 주기로 갱신
    • insertProduct, updateProduct, deleteProduct 문이 실행 시 갱신
    • Cache 사이즈: 1000 Kbyte
  • Dynamic Query
Binary Condition UnBinary Condition Loop
<isEqual>
<isNotEqual>
<isGreaterThan>
<isLessThan>
<isLessEqual>
<isPropertyAvailable>
<isNotPropertyAvailable>
<isNull>
<isNotNull>
<isEmpty>
<isNotEmpty>

<iterate>


<select id="dynamicGetAccountList“ cacheModel="account-cache"
    resultMap="account-result" >
  select * from ACCOUNT
    <isGreaterThan prepend="and" property="id" compareValue="0">
    where ACC_ID = #id#
    </isGreaterThan>
  order by ACC_LAST_NAME
</select>



Dao 구조

package com.daewoobrenic.com.program.dao;
 
import java.util.List;
 
import com.daewoobrenic.com.program.model.Program;
import com.daewoobrenic.jcf.dao.BaseSqlMapClientDAO;
 
public class ProgramDAOImpl extends BaseSqlMapClientDAO implements ProgramDAO {
 
	public int deleteProgram(String programId) {
		return executeDelete("deleteProgram", programId);
	}
 
	public int insertProgram(Program program) {
		return executeUpdate("insertProgram", program);
	}
 
	public Program selectProgram(String programId) {
		return (Program) executeQueryForObject("selectProgram", programId);
	}
 
	public List selectProgramList() {
		return executeQueryForList("selectProgramList", null);
	}
 
	public int updateProgram(Program program) {
		return executeUpdate("updateProgram", program);
	}
	
}
  • jcf.dao.ibatis.BaseSqlMapClientDAO을 상속받음.
  • sqlmap 설정파일에서 받을 수 있는 parameter형태를 넘겨야함.
  • executeQueryForObject 는 1건의 조회시 사용하며 반드시 어떤타입으로 받을지 ClassCasting을 하도록 함
  • executeQueryForList는 여러건 조회시 사용하며 List형태로 리턴함.
  • executeUpdate는 insert/update와 같이 데이터에 변경을 가할 때 사용함.

Pager Taglib Pager Tag Library v2.0

Pager Tag Library v2.0

Table of Contents

The latest release of this tag library can be found at http://jsptags.com/tags/navigation/pager/.


Overview

The Pager Tag Library is the easy and flexible way to implement paging of large data sets in JavaServer Pages (JSP). It can emulate all currently known paging styles with minimal effort. It also includes re-usable index styles that emulate the search result navigators of popular web sites such as GoogleSM, AltaVista® and Yahoo!. The Pager Tag Library does most of the work for you by dynamically organizing your data set into pages and generating a browsable index with virtually any look desired.


License

/*
 *  Pager Tag Library
 *
 *  Copyright (C) 2002  James Klicman <james@jsptags.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

The full license can be found in the file LICENSE included with this distribution or on the web at http://www.gnu.org/copyleft/lesser.txt.


Requirements

  • JavaServer Pages 1.1 compliant Web Server/Servlet Engine
  • Java 1.1 or later runtime environment

Installation

The Pager Tag Library is distributed as a ready-to-run Web Application Archive (WAR). You can deploy the distribution WAR file as-is to your JavaServer Pages 1.1 compliant server. The WAR file may also be used as the basis for a new web application. Follow the instructions bellow to integrate the Pager Tag Library into an existing web application.

The files referenced in the instructions are located in the distribution WAR file.

    WEB-INF/lib/
	pager-taglib.jar

    WEB-INF/jsp/
	pager-taglib.tld
	alltheweb.jsp
	altavista.jsp
	google.jsp
	jsptags.jsp
	lycos.jsp
	simple.jsp
	texticon.jsp
	yahoo.jsp

    images/
        jsptags.gif

Tomcat 3.x/4.x Instructions

  1. Choose the context in which to install. I'll use the "/examples" context created in the default Tomcat configuration for the following instructions.

  2. Edit the tomcat/webapps/examples/WEB-INF/web.xml file and add the following lines inside the body of the <web-app>...</web-app> tags.

    <taglib>
      <taglib-uri>
        http://jsptags.com/tags/navigation/pager
      </taglib-uri>
      <taglib-location>
        /WEB-INF/jsp/pager-taglib.tld
      </taglib-location>
    </taglib>
    
  3. Copy the file pager-taglib.tld to the tomcat/webapps/examples/WEB-INF/jsp directory.

  4. Copy pager-taglib.jar to the tomcat/webapps/examples/WEB-INF/lib directory. You may need to create a tomcat/webapps/examples/WEB-INF/lib directory if it does not already exist.

    Please Note: The 3.1 Beta version of Tomcat does not support tag libraries in jar files. The following steps will install for Tomcat 3.1 Beta.

    1. Copy pager-taglib.jar to the tomcat/webapps/examples/WEB-INF/classes directory.

    2. Change current working directory to the tomcat/webapps/examples/WEB-INF/classes directory.

    3. Extract the contents of the pager-taglib.jar file with the command:
          jar xvf pager-taglib.jar

    4. There will be a META-INF directory created during the extraction, this can be removed.

    5. The pager-taglib.jar file can now be removed from the tomcat/webapps/examples/WEB-INF/classes directory.

  5. Copy the files pager-demo.jsp and jsptags.gif to the tomcat/webapps/examples directory.

  6. Copy the file the re-usable index style files alltheweb.jsp, altavista.jsp, google.jsp, jsptags.jsp, lycos.jsp, simple.jsp, texticon.jsp and yahoo.jsp to the tomcat/webapps/examples/WEB-INF/jsp directory.

  7. Shutdown and restart tomcat.

  8. Check out http://<yourserver>/examples/pager-demo.jsp

JRun 3.0 Instructions

  1. Choose the server and web-app in which to install. The following instructions will install in JRun's default server and default web-app which is jrun/servers/default/default-app.

  2. Edit the jrun/servers/default/default-app/WEB-INF/web.xml file and add the following lines inside the body of the <web-app>...</web-app> tags.

    <taglib>
      <taglib-uri>
        http://jsptags.com/tags/navigation/pager
      </taglib-uri>
      <taglib-location>
        /WEB-INF/jsp/pager-taglib.tld
      </taglib-location>
    </taglib>
    
  3. Copy the file pager-taglib.tld to the jrun/servers/default/default-app/WEB-INF/jsp directory.

  4. Copy pager-taglib.jar to the jrun/servers/default/default-app/WEB-INF/lib directory.

  5. Copy the files pager-demo.jsp and jsptags.gif to the jrun/servers/default/default-app directory.

  6. Copy the re-usable index style files alltheweb.jsp, altavista.jsp, google.jsp, jsptags.jsp, lycos.jsp, simple.jsp, texticon.jsp and yahoo.jsp to the jrun/servers/default/default-app/WEB-INF/jsp directory.

  7. Restart JRun Default Server.

  8. Check out http://<yourserver>/pager-demo.jsp

Generic Instructions

  1. Choose the web-app in which to install. I'll use web-app/ to represent a generic web-app directory.

  2. Edit the web-app/WEB-INF/web.xml file and add the following lines inside the body of the <web-app>...</web-app> tags.

    <taglib>
      <taglib-uri>
        http://jsptags.com/tags/navigation/pager
      </taglib-uri>
      <taglib-location>
        /WEB-INF/jsp/pager-taglib.tld
      </taglib-location>
    </taglib>
    
  3. Copy the file pager-taglib.tld to the web-app/WEB-INF/jsp directory.

  4. Copy pager-taglib.jar to the web-app/WEB-INF/lib directory.

  5. Copy the files pager-demo.jsp and jsptags.gif to the web-app/ directory.

  6. Copy the re-usable index styles alltheweb.jsp, altavista.jsp, google.jsp, jsptags.jsp, lycos.jsp, simple.jsp, texticon.jsp and yahoo.jsp to the web-app/WEB-INF/jsp directory.

  7. Restart your Servlet/JSP engine.

  8. Check out http://<yourserver>/pager-demo.jsp


Examples

Please note that since the ex:searchresults tag is fictitious, the following examples will not run as is. You must provide your own looping data source. As an alternative, you may repeat as many <pg:item>...</pg:item> tags as you wish to generate a static list of items.

Example 1. A Simple Pager

[ (1) |< Previous ] [ (1) << Previous ]  1   2   3   4   5   6   7   8   9   10  [ Next >> (3) ] [ Last >| (21) ]

<%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>

<pg:pager>
  <pg:param name="keywords"/>

  <ex:searchresults>
    <pg:item>
      <%= searchResult %>
    </pg:item>
  </ex:searchresults>

  <pg:index>

    <pg:first>
      <a href="<%= pageUrl %>">[ (<%= pageNumber %>) |&lt; Previous ]</a>
    </pg:first>

    <pg:prev>
      <a href="<%= pageUrl %>">[ (<%= pageNumber %>) &lt;&lt; Previous ]</a>
    </pg:prev>

    <pg:pages>
       <a href="<%= pageUrl %>"><%= pageNumber %></a> 
    </pg:pages>

    <pg:next>
      <a href="<%= pageUrl %>">[ Next &gt;&gt; (<%= pageNumber %>) ]</a>
    </pg:next>

    <pg:last>
      <a href="<%= pageUrl %>">[ Last &gt;| (<%= pageNumber %>) ]</a>
    </pg:last>

  </pg:index>
</pg:pager>

 

Example 2. An AltaVista® Pager

Result Pages:  [<< Prev]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20  [Next >>]

<%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>

<pg:pager url="http://www.altavista.com/cgi-bin/query" maxIndexPages="20"
             export="currentPageNumber=pageNumber">
  <pg:param name="pg"/>
  <pg:param name="q"/>

  <ex:searchresults>
    <pg:item>
      <%= searchResult %>
    </pg:item>
  </ex:searchresults>

  <pg:index>
    <font face=Helvetica size=-1>Result Pages:
    <pg:prev>&nbsp;<a href="<%= pageUrl %>">[&lt;&lt; Prev]</a></pg:prev>
    <pg:pages><%
      if (pageNumber.intValue() < 10) { 
        %>&nbsp;<%
      }
      if (pageNumber == currentPageNumber) { 
        %><b><%= pageNumber %></b><%
      } else { 
        %><a href="<%= pageUrl %>"><%= pageNumber %></a><%
      }
    %>
    </pg:pages>
    <pg:next>&nbsp;<a href="<%= pageUrl %>">[Next &gt;&gt;]</a></pg:next>
    <br></font>
  </pg:index>
</pg:pager>

 

Example 3. A GoogleSM Pager

This index references Google.com for images. If you're not currently connected to the Internet you will see broken images.

Result Page:
Previous

1

2

3

4

5

6

7

8

9

10

11

Next
<%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>

<pg:pager url="http://www.google.com/search" index="half-full"
             export="currentPageNumber=pageNumber">
  <pg:param name="q"/>
  <pg:param name="sa" value="N"/>

  <ex:searchresults>
    <pg:item>
      <%= searchResult %>
    </pg:item>
  </ex:searchresults>

  <pg:index>
    <center>
    <table border=0 cellpadding=0 width=10% cellspacing=0>
    <tr align=center valign=top>
    <td valign=bottom><font face=arial,sans-serif
      size=-1>Result Page: </font></td>
    <pg:prev ifnull="true">
      <% if (pageUrl != null) { %>
        <td align=right><A HREF="<%= pageUrl %>"><IMG
          SRC=http://www.google.com/nav_previous.gif alt="" border=0><br>
        <b>Previous</b></A></td>
      <% } else { %>
        <td><IMG SRC=http://www.google.com/nav_first.gif alt="" border=0></td>
      <% } %>
    </pg:prev>
    <pg:pages>
      <% if (pageNumber == currentPageNumber) { %>
        <td><IMG SRC=http://www.google.com/nav_current.gif alt=""><br>
        <font color=#A90A08><%= pageNumber %></font></td>
      <% } else { %>
        <td><A HREF="<%= pageUrl %>"><IMG
          SRC=http://www.google.com/nav_page.gif alt="" border=0><br>
        <%= pageNumber %></A></td>
      <% } %>
    </pg:pages>
    <pg:next ifnull="true">
      <% if (pageUrl != null) { %>
        <td><A HREF="<%= pageUrl %>"><IMG
          SRC=http://www.google.com/nav_next.gif alt="" border=0><br>
        <b>Next</b></A></td>
      <% } else { %>
        <td><IMG SRC=http://www.google.com/nav_last.gif alt="" border=0></td>
      <% } %>
    </pg:next>
    </tr>
    </table>
    </center>
  </pg:index>
</pg:pager>

 


Tag Reference


pg:pager

The pg:pager tag defines the pager. Inside the pg:pager tag, use the pg:param tag to add request parameters, use the pg:item tag to define items of information, use the pg:index tag to define a navigation index, and use the pg:first, pg:prev, pg:page, pg:pages, pg:next, pg:skip and pg:last tags to define navigation elements.

Syntax

<pg:pager
  id="value"
  url="url"
  index="center|forward|half-full"
  items="int"
  isOffset="true|false"
  maxItems="int"
  maxPageItems="int"
  maxIndexPages="int"
  export="expression"
  scope="page|request"
>
...
</pg:pager>
 

Export Variables

Full Name Short Name(s) Type Scope
pageOffset offset Integer Nested
pageNumber page, number Integer Nested

id

Specifies the id of the tag. The default id is "pager". The id is used as a prefix for the pager.offset request parameter. If id is specified as "pg1" the request parameter becomes pg1.offset. See also the scope attribute.

url

Specifies the url to be used in the generated index. The default is the url of the current JSP page as returned by <%= request.getRequestURI() %> with any request parameters removed.

index

Specifies the behavior of the index. The valid values for this attribute are "center", "forward" and "half-full". The default index behavior is "center".

When the "center" behavior is specified, the size of the index is fixed to maxIndexPages or the total number of pages (whichever is lower) and the current page number is placed as close to the center of the index as possible.

When the "forward" behavior is specified, the size of the index is fixed to maxIndexPages or the number of remaining pages (whichever is lower) and the next page is the first page of the index.

When the "half-full" behavior is specified, the size of the index starts out at half of maxIndexPages or the total number of pages (whichever is lower) and grows to maxIndexPages as pages are browsed. The "half-full" behavior emulates GoogleSM.

items

Specifies the number of items available in the data set. This is useful when the data set size is known and can be retrieved in page sized chunks. When this attribute is set, the index can be displayed before and after the items.

isOffset

Specifies that the first pg:item will be offset to the current pager offset. This is useful when the data source is a database that supports the limit & offset clauses. The default value is false.

maxItems

Specifies the maximum number of items to be available in the generated index. The default and maximum value is 2147483647.

maxPageItems

Specifies the maximum number of items to be displayed in each page. The default value is 10.

maxIndexPages

Specifies the maximum number of pages to be included in the generated index. The default value is 10.

export

Specifies the variables to export. See also the export variables section.

scope

Specifies the scope of exported variables. The valid values for this attribute are "page" and "request". The default is "page". If scope is "request" the pg:index and navigation tags can be included from another JSP page.


pg:param

The pg:param tag is used inside the pg:pager tag to add request parameters to each page url in the index.

Syntax

<pg:param
  id="value"
  name="value"
  value="value"
 />

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

name

Specifies the required request parameter name.

value

Specifies an optional static value. The default is the request parameter specified by the name attribute.


pg:item

The pg:item tag is used inside the pg:pager tag to define page items. If the item is out of range for the current page it is not displayed.

Syntax

<pg:item
  id="value"
>
...
</pg:item>

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.


pg:index

The pg:index tag is used inside the pg:pager tag to specify the index. If all of the items fit on one page the index is not displayed.

Syntax

<pg:index
  id="value"
  export="expression"
>
...
</pg:index>
 

Export Variables

Full Name Short Name Type Scope
itemCount items Integer Nested
pageCount pages Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

export

Specifies the variables to export. See also the export variables section.


pg:first

The pg:first tag is used inside the pg:index or pg:pager tag to create a link to the first page.

Syntax

<pg:first
  id="value"
  unless="current|indexed"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:first>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

unless

Specifies when the first page link should not be displayed. If "current" is specified, the link will not be displayed if the first page is the current page. If "indexed" is specified, the link will not be displayed if the first page is displayed in the index. The default is to always display the link.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on the the page. See also the export variables section.


pg:prev

The pg:prev tag is used inside the pg:index or pg:pager tag to create a link to the previous page. If there is no previous page the exported variables will be null.

Syntax

<pg:prev
  id="value"
  ifnull="true|false"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:prev>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

ifnull

Specifies whether or not to evaluate the body if there is no previous page to the current page. The default is false, do not evaluate body. If the value is true then the body is evaluated when there is no previous page and the exported variables are set to null.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on the page. See also the export variables section.


pg:page

The pg:page tag is used inside the pg:index or pg:pager tag to create a link to the current page or export information about the current page.

Syntax

<pg:page
  id="value"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:prev>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on the page. See also the export variables section.


pg:pages

The pg:pages tag is used inside the pg:index or pg:pager tag to create a link to each page in the index. The body of the pg:pages tag is processed for each page in the index. The export variable pageNumber can be compared with page number exported from pg:pager to determine the current page.

Syntax

<pg:pages
  id="value"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:pages>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on this page. See also the export variables section.


pg:next

The pg:next tag is used inside the pg:index or pg:pager tag to create a link to the next page. If there is no next page the exported variables will be null.

Syntax

<pg:next
  id="value"
  ifnull="true|false"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:next>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

ifnull

Specifies whether or not to evaluate the body if there is no next page to the current page. The default is false, do not evaluate body. If the value is true then the body is evaluated when there is no next page and the exported variables are set to null.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on this page. See also the export variables section.


pg:last

The pg:last tag is used inside the pg:index or pg:pager tag to create a link to the last page.

Syntax

<pg:last
  id="value"
  unless="current|indexed"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:last>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

unless

Specifies when the last page link should not be displayed. If "current" is specified, the link will not be displayed if the last page is the current page. If "indexed" is specified, the link will not be displayed if the last page is displayed in the index. The default is to always display the link.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on this page. See also the export variables section.


pg:skip

The pg:skip tag is used inside the pg:index or pg:pager tag to create a link to the page number calculated by adding the value of the pages attribute to the current page number. If the target skip page does not exist the exported variables will be null.

The pg:prev and pg:next tags operate relative to the current offset and are preferred to pg:skip for single page increments. If the current offset is not a multiple of maxPageItems due to a dynamic change in the maxPageItems value, the pg:next and pg:prev tags ensure that no items are skipped.

Syntax

<pg:skip
  id="value"
  ifnull="true|false"
  pages="int"
  export="expression"
>
<%= pageUrl %>
<%= pageNumber %>
...
</pg:skip>
 

Export Variables

Full Name Short Name(s) Type Scope
pageUrl url String Nested
pageNumber page, number Integer Nested
firstItem first Integer Nested
lastItem last Integer Nested

id

When the scope for pg:pager is "request" and the pg:pager id attribute is set, this specifies the id for the pg:pager tag. The value of id must match the value specified for the pg:pager tag.

ifnull

Specifies whether or not to evaluate the body if the calculated skip page does not exist. The default is false, do not evaluate body. If the value is true and the skip page does not exist, the body is evaluated and the exported variables are set to null.

pages

Specifies the number of pages to skip relative to the current page. Negative numbers can be used to skip backwards.

export

Specifies the variables to export. The default is to export pageUrl and pageNumber. The firstItem and lastItem variables are the first and last item numbers on this page. See also the export variables section.


export variables

The export attribute is a flexible way access the tag variables that are available. A special feature of the export attribute is the ability to control the name of exported variables.

The pg:pager tag has two export variables, pageOffset and pageNumber. The export expression used to export the pageOffset variable would simply be export="pageOffset". This would cause the pageOffset variable to be available as <%= pageOffset %>. Both pg:pager variables can be exported with export="pageOffset,pageNumber". Each variable name may be separated by either a comma ",", semicolon ";", or spaces " ". A final semicolon may optionally appear at the end of the expression.

The following export expressions are equivilent.

export="pageOffset,pageNumber"
export="pageOffset;pageNumber"
export="pageOffset pageNumber"
export="pageOffset,pageNumber;"
export="pageOffset;pageNumber;"
export="pageOffset, pageNumber;"

All of the variables have one or more short names which can be specified. The short name of pageOffset is offset. The short names for pageNumber are page and number. If the short name is specified, the variable is declared using the short name. The export expression export="offset" would cause the pageOffset variable to be available as <%= offset %>.

The export attribute also enables the specification of custom variable names. This may be used to avoid variable name conflicts or to specify variable names in your preferred language. The export expression export="versatz=offset" would cause the pageOffset variable to be available as <%= versatz %>. The long or short variable name can be used in the expression, for example export="seiteVersatz=pageOffset" is also valid.

Examples of valid expressions.

export="pageOffset;"
export="offset, pageNumber"
export="versatz=offset, zahl = number;"

Examples of invalid expressions.

export="pageOffset,"
export="pageOffset pageNumber"
export="pageOffset, pageNumber,"
export="nonexistentVariable"
export="offset=foo"
(should be foo=offset)


Upgrading to v2.0

Export Variables

The default export behavior of the pg:pager tag has been changed. It no longer exports pagerOffset, pagerPageNumber and pagerMaxItems by default.

To emulate the previous behavior, add the pg:pager attribute:

export="pagerOffset=pageOffset,pagerPageNumber=pageNumber"

The export of pagerMaxItems has been dropped in this release due the value originating outside of the Pager Tag Library. If you need access the value of maxItems simply re-use the input value given to the pg:pager tag.

Recompiling JSP Files

JSP files compiled with an older release of the Pager Tag Library may need to be recompiled. Recompiling may be necessary even when no modifications are required to the JSP file. The simplest way to cause a recompile is by touching the JSP file to update it's timestamp. Updating the timestamp can be done by editing and saving the JSP file.


Troubleshooting

Translation Time Errors

If you get translation time errors reported for your JSP file, it may be a problem with your JavaServer Pages implementation.

Many JSP implementations do not correctly handle conversions of attributes in custom actions. This means that instead of automatically converting an attribute such as maxPageItems="5" to the correct (in this case) native type of int, the JSP engine incorrectly attempts to pass the attribute as a String.

The correct behavior has been clarified by JSP 1.1a Errata Issue #7 which states:

...
Conversions in attributes in custom actions

What type of conversions are applied to attribute values of a custom action. Specifically, what is done to a request-time attribute value, and what is done to a literal string.

Resolution

A request-time attribute value is passed with no conversion.

A literal string is converted following the rules in Table 2-4, section 2.13.2.
...

If you encounter this issue, I would recommend reporting the bug to your JSP server vendor.

In the mean time, you can work around the issue by using request-time values for any attributes that expect an int or boolean value. To specify a request time attribute simply wrap the value in <%= %>. Attributes such as maxPageItems="5" would become maxPageItems="<%= 5 %>" and ifnull="true" would become ifnull="<%= true %>".


Release History

  • December 20th, 2002 v2.0 Feature Release

    • New pg:pager attributes: index, items, export and scope.

    • New tags: pg:page, pg:first, pg:last and pg:skip.

    • New export variables: itemCount, pageCount, firstItem and lastItem.

    • New flexible export variable declaration syntax.

    • Support for external index style pages.

    • Eight included re-usable index styles.

    • Support for indexes before items.

    • Support for multi-value request parameters.

    • Numerous performance optimizations including reduced object creation, improved class hierarchy and thorough finalization of methods and classes.

    • Compatibility with JavaServer Pages version 1.2 tag caching.

    • Changed default exports of pg:pager tag and removed export variable pagerMaxItems.

    • Web Application Archive (WAR) distribution format.

  • September 26th, 2000 v1.1 Maintenance Release

    • Fixed bug which caused a ClassCastException by calling javax.servlet.jsp.tagext.TagData.getAttributeString() on a request-time attribute.

    • Modified pager-demo.jsp to use request-time attributes which are more compatible with the current releases of commercial JSP servers. (see JSP 1.1a Errata Issue #7)

    • Updated installation instructions for Tomcat.

    • Added installation instructions for JRun 3.0.

    • Added generic installation instructions.

  • March 29th, 2000 v1.0 Initial Release


Copyright © 2002 James Klicman.

2010년 7월 30일 금요일

Spring에서 파일을 포함한 Form 을 전송하고 업로드 하기


1. 먼저 form 태그에 다음의 프로퍼티를 추가한다.

 

enctype="multipart/form-data"

인코딩 타입이 Multipart 인 경우 파라미터나 업로드한 파일을 구할려면 전송 데이터를 알맞게 처리해 주어야 한다. 스프링은 Multipart 지원 기능을 제공하고 있기 때문에, 이 기능을 이용하면 추가적인 처리 없이 Multipart 형식으로 전송된 파라미터와 파일 정보를 쉽게 구할 수 있다.

 

2. MultipartResolver 설정

 

<bean id="multipartResolver"

 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

</bean>

Multipart 지원 기능을 사용하려면 먼저 MultipartResolver를 스프링 설정파일에 등록해 주어야 한다. MultipartResolever 는 Multipart 형식으로 데이터가 전송된 경우, 해당 데이터를 스프링 MVC 에서 사용할 수 있도록 변환해준다.

 

라이브러리에 다음을 추가한다.

 

commons-fileupload / commons-fileupload

commons-io            / commons-io            <- 1.4 version

 

2.1. MultipartResolver의 Property

 Property  Type  Descript
 maxUploadSize  long  최대 업로드 가능한 바이트 크기. -1 은 체한이 없음을 의미한다, Default 는 -1
 maxInMemorySize  int  디스크에 임시 파일을 생성하기 전에 메모리에 보관할 수 있는 최대 바이트 크기, 기본값은 10240 바이트이다.
 defaultEncoding  String  요청을 파싱할 때 사용할 캐릭터 인코딩. 지정하지 않을 경우 HttpServletRequest.setCharacterEncoding() 메서드로 지정한 캐릭터 셋이 사용된다. 아무 값도 없을 경우 ISO-8859-1을 사용한다.

 

 

3. Controller 에서 데이터 받아오기.

 

컨트롤러의 파라미터에 값을 받아 넣을 때 다음의 소스를 입력한다.

@RequestParam("[inputName]") MultipartFile [paramName]

 

다음은 MultipartFile 인터페이스가 제공하는 주요 메서드 이다.

 

 Method  Descript
 String    getName()  파라미터의 이름을 구한다.
 String    getOriginalFilename()  업로드 한 파일의 이름을 구한다.
 boolean isEmpty()  업로드 한 파일이 존재하지 않는 경우 true를 리턴한다.
 long      getSize()  업로드 한 파일의 크기를 구한다.
 byte[]   getBytes() throws IOException  업로드 한 파일의 데이터를 구한다.
 InputStream getInputStream() throws IOException

 업로드 한 파일 데이터를 읽어오는 InputStream을 구한다,

 InputStream의 사용이 끝나면 알맞게 종료해 주어야 한다.

 void      transferTo(File dest) throws IOException  업로드 한 파일 데이터를 지정한 파일에 저장한다.

 

if (multipartFile.isEmpty)) {

//업로드 한 파일데이터를 구하는 가장 단순한 방법은 MultipartFile.getBytes() 메서드를 이용하는 것이다. 바이트 배열을 구한 뒤에 파일이나 DB 등에 저장하면 된다.

   byte[] fileData = multipartFile.getByte();

   ...

}

 

if (multipartFile.isEmpty)) {

//업로드 한 파일 데이터를 특정 파일로 저장하고 싶다면 MultipartFile.transferTo() 메서드를 사용하는 것이 편리하다.

   File file = new File(fileName);

   multipartFile.transferto(file);

   ...

}

 

 

 

Validation Check

Validation Check 는 Data의 검증을 뜻한다.

 

Validation Check의 방법에는 크게 3가지 가 있는데

 

    1. Client-Side VC : UI에서 JS를 이용해 체크한다.
    2. Server-Side VC : Java 에서 체크한다.
    3. Database Constraint VC : Key, check, Default 등으로 체크 한다.

위 세가지중 하나라도 배제한다면 잘못된 프로그래밍 습관을 가진것이다.

2010년 7월 29일 목요일

Integer 타입에서 자주 쓰는 API

1. 숫자를 문자로 변환하기.

입력되거나 변수에서 초기화 또는 대입된 숫자를 문자로 바꿀 수 있다.

  1. 문자변수 = Integer.toString(숫자 또는 숫자변수) // 숫자 또는 숫자변수를 문자변수에 형을 변환해서 저장한다.

Spring 타입에서 자주 쓰는 API

1. String 을 숫자로 변환하기.

int num = Integer.parseInt(문자);

 

숫자를 문자로 변환하거나, nextLine() 으로 입력받은 문자를 숫자로 변환하고자 할때 사용된다.

즉, 문자 부분에 들어갈 수 있는 것은 두가지가 있다.

순수한 문자열 또는 Scanner 가 있다.

 

2. 문자열 비교하기.

Scanner 로 입력받은 문자열은 단순한 문자열로는 비교할 수 없다.

하여 Scanner 로 입력받은  문자열은 String 타입의 특정 메서드를 사용하는데

종류는 크게 3가지가 있다.

  1. String.compareTo(문자)  // 문자와 문자사이에 존재하는 문자의 개수를 리턴한다. 즉, 반환값이 0이라면 같은 문자열이다.

  2. String.equals(문자) // 문자와 문자를 순수히 비교한다. 같다면 true, 틀리면 false 를 반환한다.

  3. String.equalsIgnoreCase(문자) // 문자와 문자를 비교하는데 대소문자 구분을 하지 않는다. 다시말하면 equals 는 대소문자를 구분한다.

 

3. 문자 추출하기

문자열은 앞의 문자와 뒤의 문자를 비교할 수 있다. 또한, 시작 위치를 지정하고 추출할 길이를 추출하면 해당 길이만큼의 문자를 추출해낼 수 있다.

  1. String.startsWith(문자) // String 이 문자로 시작하는지 판단한다. 참이라면 true, 거짓이면 false 를 반환한다.

  2. String.endsWidth(문자) // String 이 문자로 끝나는지 판단한다. 참이라면 true, 거짓이면 false 를 반환한다.

  3. String.subString(시작위치, 마지막위치) // String 에서 시작위치부터 마지막 위치까지의 문자열을 반환한다.

  3. 예제 abcdefg.subString(0, 3) =>> abc

Toad 단축키

toad사용법

 SQL EDITOR상에서의 편리한 단축키

ESC: 열린 윈도우 닫기
F1: 모든 단축키를 보여준다.
F2: FULL SCREEN
F4: Table, View, Proc, Funct, Package를 DESC(테이블명에 커서를 둔 상태에서 해야함)
F6: SQL Editor와 결과창간의 전환
F7: 화면을 모두 CLEAR
F8: 실행했던 SQL들의 HISTORY
F9: 모든 쿼리 실행(Ctrl+Enter는 현재 쿼리만 실행)
Ctrl+F9: 실제 쿼리를 실행하지 않고 validate함
Ctrl+. : table Completion (매칭되는 테이블목록 출력)
Ctrl+T : Columns Dropdown (해당테이블의 컬럼목록 표시)
Alt+Up : History Up (리눅스 bash의 UP키와 같다.)
Alt+Down: History Down (리눅스 bash의 DOWN키와 같다.)
Ctrl+Tab: MDI Child윈도간 전환

그냥 'desc 테이블명' 을 치면, 팝업윈도로 해당 테이블의 컬럼목록윈도가 표시된다.
이때, 해당 컬럼을 double-click하면 SQL Editor로 반영된다.

"테이블명."까지 입력하고 좀 있으면, 해당 테이블의 컬럼목록이 표시된다.
마치 프로그래밍툴에서 클래스내 멤버들의 목록을 표시하듯이..
Ctrl+T는 출력된 목록을 취소했을 경우, 다시 불러낼때 쓰인다.

test, member 2개의 테이블이 있다고 하자.
select * from t까지 입력하고 Ctrl+.를 치면 select * from test로 테이블명을 완성시켜준다.
system계정에서는 안되더군.. 일반계정만 가능했다.

SQL문을 실행시

Ctrl+Enter
현재 커서의 SQL문 실행
여러개의 SQL문이 있을때, SQL문들을 개행문자로 분리해주면 된다.
해당 커서에서 개행문자가 있는 곳까지만 하나의 SQL문으로 간주한다.

F9
SQL Editor의 SQL문 실행하여 Grid에 출력.
여러 SQL문들을 개행문자로 구분하지 않는다는 것을 제외하면, 위의 Ctrl+Enter와 동일하다.
에디터내의 모든 SQL문은 하나로 취급하므로, 여러 개의 SQL문이 있으면 실행할 SQL문만 Selection하여 실행(F9)해준다.

F5
SQL Editor내의 모든 SQL문 실행. 여러개의 SQL문들을 모두 실행하여 SQL*PLUS와 같이 출력해준다.
이것은 출력이 Grid로 표시되지 않고 Editor윈도에 표시되므로, SQL*PLUS의 출력과 같이,
다른 편집기로의 복사/붙여넣기 할때 사용하면 유용하다.

Oracle 페이징 쿼리

페이징 기법이란

데이터가 100건이 있다고 가정한다면, 한페이지당 10개씩 보여줄수 있게하는 기법을 말합니다.

1페이지에는 0~10까지. 2페이지에는 11~20 까지.. 10페이지에는 91~100 까지의 레코드를 보여주는 것을 말합니다.

 

아래는 페이징 기법을 구현할 수 있는 쿼리문입니다.

 

 

오라클에서 paging을 처리하기 위해서는 오라클에서 제공되는 rownum을 사용하게 됩니다.

하지만 rownum을 잘못알고 사용을 하게 되면 저처럼 삽질을 계속 하게 된다는 ^^;;

예를들면...
  SELECT *
  FROM (
            select board_seq, board_name, insert_date
            from t_board
            order by insert_date desc
            )
   WHERE ROWNUM >= 1 AND ROWNUM <= 10

  이렇게 쿼리문을 날리면 데이터가 나옵니다.

  하지만 ..

  SELECT *
  FROM (
            select board_seq, board_name, insert_date
            from t_board
            order by insert_date desc
            )
   WHERE ROWNUM >= 11 AND ROWNUM <= 20

   이렇게 쿼리문을 날렸을때 그냥 보기에는 나올것 같습니다. 하지만 아무런 데이터가
   나오지를 않습니다.^^; 아주 황당합니다.

그래서 많이쓰는 방법으로... 첫번째..

  SELECT *
  FROM (
            select rownum as rnum, board_seq, board_name, insert_date
            from t_board
            order by insert_date desc
            )
   WHERE rnum>= 11 AND rnum <= 20

  서브쿼리에서 rownum을 구해 동일한 방법으로 where 조건을 주면 아주 잘 나옵니다.

또다른 방법.. 두번째..

  row_number() over(정렬을 위한 order by) 를 사용하면 됩니다.

  SELECT *
  FROM (
            select row_number() over(order by insert_date desc) as rnum, board_seq,
                     board_name, insert_date
            from t_board
            )
   WHERE rnum>= 11 AND rnum <= 20

첫번째 방법과 두번째 방법을 했을경우 결과는 동일합니다.

차이점이 있다면 두번째 방법에서 row_nuber() over()를 이용해서 over()안에 있는
order by 순으로 rownum을 새롭게 구하는것입니다.

* 참고 : row_number()는 오라클 8.1.6.0.0 이상에서 사용이 가능합니다.

EOF, BOF(RecordSet)

EOF, BOF란?

EOF는 End Of File의 약자로 커서가 레코드의 제일 마지막에 위치해있는것을 말합니다.

이때 레코드의 마지막에 커서가 위치해있다면 True를 반환하게 되며, 그렇지 않을경우는 False를 반환하게됩니다.

 

 Field Field Field EOF
 Record  Record  Record  False
 Record  Record  Record  False
       True

 

위의 표처럼 필드내에 레코드가 있다면 EOF는 False를 반환하게 됩니다.

반면, 필드내에 레코드가 없다면 True를 반환하게 됩니다.

 

데이터베이스는 모든 필드마다 여분의 셀(cell)을 두고 있습니다.

레코드가 앞으로 얼마나 더 추가가 될지 모르기때문에 그에 대비하여 여분의 레코드를 두게 되는데

커서가 여기에 위치할경우 EOF = True 를 반환하게 됩니다.

 

BOF는 어떻게 될까요?

BOF는 Begin Of File의 약자로 커서가 레코드의 제일 첫 행에 위치해있을 경우를 말합니다.

커서가 제일 첫 행에 위치할경우 True를 반환하고, 그렇지 않을 경우 False를 반환합니다.

 

1.

 Field Field Field BOF
 Record  Record  Record False
 Record  Record  Record
       

 

2.

 Field Field Field EOF



True




 

Oracle 함수 정리

CEIL

::
소수점 이후의 값은 무조건올림하는 함수.

 

MOD

::
두 수를 나눈 나머지 값을 구하는 함수.

 

POWER

::
승수 값을 구하는 함수.

[
] SQL> select POWER(3, 2), POWER(3, -2) from dual;

[
결과]9          .11111111

 

ROUND

::
반올림 값을 구하는 함수.

[
] SQL> select ROUND(345.123, 0), ROUND(345.123,2), round(345.123, -1) from dual;

[
결과]345          345.12          350

 

TRUNC

::
버림 값을 구하는 함수.

[
] SQL> select TRUNC(345.123, 2), TRUNC(345.123,0), trunc(345.123, -1) from dual;

[
결과]345.1          345          340

 

SIGN

::
해당 값이 양수면 1, 음수면 -1, 0이면 0을 돌려준다.

[
] SQL> select SIGN(345.123), SIGN(0),SIGN(-345.123) from dual;

[
결과]1          0          -1

 

CHR, ASCII

:: ASCII
은 문자로, 문자는 ASCII 값으로반환하는 함수.

[
] SQL> select CHR(65), ASCII('A') from dual;

[
결과]A          65

 

LOWER, UPPER

::
문자열을 소문자와 대문자로 반환하는 함수.

[
] SQL> select LOWER('My'), UPPER('My') from dual;

[
결과]my          MY

 

LPAD(char1, n, char2)

:: n
자리 만큼의 공간에서 char1을 오른쪽에 붙이고, 나머지 공간을 char2로 채운다.

RPAD(char1, n, char2)

:: n
자리 만큼의 공간에서 char1을 왼쪽에 붙이고,나머지 공간을 char2로 채운다.

[
] SQL> select LPAD('LDH', 10, '#'), RPAD('LDH',10, '#') from dual;

[
결과]#######LDH          LDH#######

 

LTRIM, RTRIM

::
각 각 오른쪽(LTRIM)과 왼쪾(RTRIM)의공백(Space)을 제거한다.

 

REPLACE(char1, char2, char3)

:: char1
문자열에서 char2 char3으로치환하는 함수.

[
] SQL> select REPLACE('Orange', 'O', 'A') fromdual;

[
결과] Arange

 

SUBSTR(char1, n, m)

:: char1
문자열의 n번째부터 시작해서 m번째까지의문자열을 리턴한다.

[
] SQL> select SUBSTR('오라클Oracle', 1, 3) from dual;

[
결과] '오라클'

[
] SQL> select SUBSTR('오라클Oracle', 7, 9) from dual;

[
결과] 'acl'

[
] SQL> select SUBSTR('오라클Oracle', 10) from dual;

[
결과] 'e'

 

SUBSTRB

::
바이트 단위로 계산하여 문자열을 치환하는 함수.

[
] SQL> select SUBSTRB('오라클Oracle', 1, 3) from dual;

[
결과] ''

[
] SQL> select SUBSTRB('오라클Oracle', 7, 9) from dual;

[
결과] ' Or'

[
] SQL> select SUBSTRB('오라클Oracle', 10) from dual;

[
결과] 'acle'

 

LENGTH, LENGTHB

::
문자열의 길이를 나타낸다.

[
] SQL> select LENGTH(운동(축구)), LENGTH(운동(축구))from dual;

[
결과]6          10

 

INSTR(char1, char2, n, m)

:: char1
에서 char2가 포함된 문자열의 위치가char1을 기준으로 n번째 위치부터 시작해서 m번째로 char2와 같은 위치를 돌려준다.

 

INSTRB(char1, char2, n, m)

::
바이트 단위로 내용은 위와 같다.

[
] SQL> INSTR('간장콩장공장장', '', 1, 2), INSTRB(간장콩장공장장', '', 1, 2) from dual;

[
결과]4          7

[
] SQL> INSTR('Corporate Floor', 'or', 3, 2),INSTRB('Corporate Floor', 'or', 3, 2) from dual;

[
결과]11          11

[
] SQL> INSTR('오라클 Oracle','r', 1, 1), INSTRB('오라클 Oracle', 'r', 1, 1) from dual;

[
결과]6          9

 

SYSDATE

::
현재의 일자와 시간을 의미하고, 기본값으로 오늘일자를 돌려준다.

[
] SQL> select SYSDATE from dual;

[
결과] 04/04/19

[
] SQL> select to_char(SYSDATE, 'YYYY-MM-DDHH24:MI:SS') from dual;

[
결과] 2004-04-19 00:44:20

 

LAST_DAY

::
해당 월의 마지막 날짜를 돌려준다.

[
] SQL> select LAST_DAY(SYSDATE), SYSDATE fromdual;

[
결과]04/04/30          04/04/19

 

MONTH_BETWEEN(date1, date2)

:: date1
date2를 월 단위로 계산하여 그 값을 리턴한다. 만약, date1 date2보다크면, 양수의 결과가 나온다.

[
] SQL> select MONTH_BETWEEN('2004-01-19','2004-04-19') from dual;

[
결과] -3

 

ADD_MONTHS(date, n)

:: date
n개월 후의 값을 리턴한다.

[
] SQL> select ADD_MONTHS(SYSDATE, 2), SYSDATE fromdual;

[
결과]04/06/19          04/04/19

 

NEXT_DAY(date, n)

:: date
를 기준으로 n요일에 해당하는 다음 날짜를 리턴한다.

[
] SQL> select NEXT_DAY(SYSDATE, 2),NEXT_DAY(SYSDATE, 7), SYSDATE from dual;

[
결과]04/04/20          04/04/25          04/04/19

 

TO_CHAR(n), TO_CHAR(n, format), TO_CHAR(date, format)

:: n
format 형식의 문자로 바꾸는 함수.

[
] SQL> select TO_CHAR(123.456) from dual;

[
결과] 123

[
] SQL> select TO_CHAR(123456.789, '999,999.9999')from dual;

[
결과] 123, 456.7890

[
] SQL> select TO_CHAR(SYSDATE, 'YYYY') from dual;

[
결과] 2004

 

TO_NUMBER(char), TO_NUMBER(char, format)

:: char
format 형식의 숫자로 바꾸는 함수.

[
] SQL> select TO_NUMBER('123.12') from dual;

[
결과] 123.12

[
] SQL> select TO_NUMBER('123.12', '999.999') fromdual;

[
결과] 123.120

 

TO_DATE(char), TO_DATE(char, format)

[
] SQL> select TO_DATE('20040419') from dual;

[
결과] 2004-04-19 00:00:00

[
] SQL> select TO_DATE('20040419', 'YY/MM/DD') fromdual;

[
결과] 04/04/19

 

AVG(column_name)

::
해당 컬럼의 평균값을 리턴한다.

 

MAX(column_name)

::
해당 컬럼에서 제일 큰 값을 리턴한다.

 

MIN(column_name)

::
해당 컬럼에서 제일 작은 값을 리턴한다.

 

SUN(column_name)

::
해당 컬럼의 합계를 리턴한다.

 

COUNT(column_name)

::
조회건수를 리턴한다.

 

NVL(column_name,
대신할 데이터)

::
해당 컬럼이 Null일 경우, 대신할 문자나숫자 등을 대신 사용한다.

 

DECODE

::
연속된 조거문이라고 할 수 있는데, 가장 자주 쓰이는 함수 중에 하나이다.

[
] SQL> select DECODE(idx, 10, '', 20, '', 30, '',40, '') from dual;

[
설명] idx 10이면 ''이고, 20이면 ''이고, 30이면 ''이고, ...

 

USERENV

::
현재 세션의 환경 정보를 반환한다.

ENTRYID :
사용 가능한 Auditing entry Identifier를 반환.
LABEL :
현재 세션의 Label을 반환.
LANGUAGE :
현재 세션에서 사용중인 언어와 테리토리 값을 반환.
SESSIONID : Auditing(
감사) Session ID를 반환.
TERMINAL :
현재 세션 터미널의 OS ID를 반환.

 

GREATEST(n1, n2, n3, ...)

::
숫자나 문자 아무거나 나열하면 그 중에 가장 큰 값을 반환한다.

 

LEAST(n1, n2, n3, ...)

::
숫자나 문자 아무거나 나열하면 그 중에 가장 작은 값을 반환한다.

 

UID, USER

::
사용자 ID와 사용자의 OWNER를 돌려준다.