출처 : http://www.jakartaproject.com/board-read.do?boardId=javascripttip&boardNo=119681533125923&command=READ&t=1196858804183


질문) alert("" == 0) ;

        이렇게 하면 true , false 둘중 어느것이 나올까요?


  답은 true 입니다. 이상하지 않나요?



  if("" == 0 ) // with casting

  if("" === 0 )  // without casting

  즉 ""이 형변환이 되어 0으로 되서 true로 되었습니다.


  또  alert("" === 0) ;  이면  false가 됩니다.


 그리고 ""이 형변환해서 0이 된 이유는 아래와 같습니다.


 자바스크립트에서 null과 undefined의 차이점을 알아야 하는데요


In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:



var TestVar;
alert(TestVar);                   //shows undefined
alert(typeof TestVar);          //shows undefined


null is an assignment value. It can be assigned to a variable as a representation of no value:



var TestVar = null;
alert(TestVar);             //shows null
alert(typeof TestVar);    //shows object


From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Unassigned variables are initialized by JavaScript with a default value of undefined.

JavaScript never sets a value to null. That must be done programmatically.

As such, null can be a useful debugging tool. If a variable is null, it was set in the program, not by JavaScript.



null values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: 0
String: “null”


undefined values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: NaN
String: “undefined”


=============================================================================

----------------------------------------------------------------
 달팽이 
 
 이것도 궁금한데요.
undefined 를 확인할때
if(obj == undefined || obj == "undefined"){ ... }
이런식으로 체크를 해야하나요?
어떻게 보면
if(obj == null || obj == "null"){ ... }
이것과도 같은데 말이죠.
사이트 돌아다 보면 이런코드를 종종 보는데, 이것이 필요한건지..
----------------------------------------------------------------
 
 GoodBug   
undefined 체크는 다음과 같이 하세요
if (object === undefined)
혹은
if (typeof object == 'undefined')
 
null 비교는
if (object == null)을 해도 되지만 확실히 하기 위해서는
if (object === null)을 하는것이 좋습니다
=== 은 값 뿐만 아니라 type 까지 비교해주는겁니다
----------------------------------------------------------------

출처 : http://www.jakartaproject.com/article/jsptip/119336284359281


iBatis 에서 SQL 로깅시 이뿌게 보이기

iBatis에서 SQL로깅은 한줄로 표현되기 때문에 디버깅이 불편합니다
이를 해결하고자 몇가지 알아봤지만 소스를 직접 수정하는수 밖에 없더군요

I. 소스받기
  • http://www.ibatis.com

II. 소스 수정 리스트
  • com.ibatis.common.jdbc.logging.ConnectionLogProxy.java
  • com.ibatis.common.jdbc.logging.PreparedStatementLogProxy.java
  • com.ibatis.common.jdbc.logging.StatementLogProxy.java
  • com.ibatis.sqlmap.engine.mapping.sql.SqlText.java
  • com.ibatis.sqlmap.engine.mapping.sql.stat.StaticSql.java

1. com.ibatis.common.jdbc.logging.ConnectionLogProxy.java
//log.debug("{conn-" + id + "} Preparing Statement: " + removeBreakingWhitespace((String) params[0]));
log.debug("{conn-" + id + "} Preparing Statement: " + ((String) params[0]));
...
//log.debug("{conn-" + id + "} Preparing Call: " + removeBreakingWhitespace((String) params[0]));
log.debug("{conn-" + id + "} Preparing Call: " + ((String) params[0]));

주석처리 후 removeBreakingWhitespace 함수를 제거합니다
removeBreakingWhitespace 함수가 '\n'를 ' '로 replace 시킵니다

2. com.ibatis.common.jdbc.logging.PreparedStatementLogProxy.java

//log.debug("{pstm-" + id + "} Executing Statement: " + removeBreakingWhitespace(sql));
log.debug("{pstm-" + id + "} Executing Statement: " + (sql));

마찬가지로 removeBreakingWhitespace 함수를 제거합니다

3. com.ibatis.common.jdbc.logging.StatementLogProxy.java

//log.debug("{stmt-" + id + "} Statement: " + removeBreakingWhitespace((String) params[0]));
log.debug("{stmt-" + id + "} Statement: " + ((String) params[0]));

역시나 removeBreakingWhitespace 함수를 제거합니다

4. com.ibatis.sqlmap.engine.mapping.sql.SqlText.java

public void setText(String text) {
    //this.text = text.replace('\r', ' ').replace('\n', ' ');
    this.text = text;
    this.isWhiteSpace = text.trim().length() == 0;
}

replace 하는 부분을 주석처리해 놓고 this.text = text; 를 추가합니다

5. com.ibatis.sqlmap.engine.mapping.sql.stat.StaticSql.java

public StaticSql(String sqlStatement) {
    //this.sqlStatement = sqlStatement.replace('\r', ' ').replace('\n', ' ');
    this.sqlStatement = sqlStatement;
}

마찬가지로 replace 하는 부분을 주석처리 하고 this.sqlStatement = sqlStatement; 를 추가시킵니다

III. 수동으로 컴파일 후 jar 압축하기
1. 다운받은 ibatis-2.3.0.677 를 압축을 풉니다
2. C:\ibatis-2.3.0.677\src\ibatis-src.zip의 압축을 풉니다
3. C:\ibatis-2.3.0.677\src\ 이하 위의 리스트에 있는 소스를 수정합니다
4. C:\ibatis-2.3.0.677\src\의 수정된 5개의 자바 소스를 C:\ibatis-2.3.0.677\lib\로 카피 합니다
5. C:\ibatis-2.3.0.677\lib\ibatis-2.3.0.677.jar 압축을 풉니다
6. C:\ibatis-2.3.0.677\lib\의 현재 상태입니다


7. cmd 창을 열어 C:\ibatis-2.3.0.677\ 이동 후 컴파일 합니다
javac -classpath "." -d ./ *.java

8. jar 압축 합니다
jar cvf ibatis-2.3.0.677.jar ./

ibatis.jar를 생성후 적용해 보면 한줄로 쭉 나오던 SQL이 아래와 같이 깔끕하게 나옵니다

2007-10-26 10:34:17,328 DEBUG [http-80-Processor24] sql.Connection    (JakartaCommonsLoggingImpl.java:27)     - {conn-100009} Preparing Statement:
                SELECT
                         COMMON_GB
                        ,COMMON_GB_NM
                        ,USE_YN
                        ,REGISTER_USER
                        ,LAST_UPDATE_USER
                        ,REGISTER_DT
                        ,LAST_UPDATE_DT
                FROM CMR_COMMONCD_MAST
                ORDER BY COMMON_GB

재생성한 jar파일 첨부합니다

com.ibatis.common.jdbc.logging.*  패키지에 JDBC관련 로깅 java들이 있습니다
ResultSet 로깅등 여러가지 부분들을 수정 할 수 있습니다
출처 : http://www.jakartaproject.com/article/javascripttip/119346308726768

1. 변수는 로컬에 명시적으로 정의한다.
함수내에서 사용되는 지역 변수가 있다면 명시적으로 var 표시를 해주도록 합니다. 그렇지 않을 경우 브라우저는 상위 scope를 모두 뒤져서 상위에 해당 변수가 정의되어있는지 확인합니다.

 

2. 가능하다면 일단 캐싱한다.
DOM은 느리므로 가급적이면 DOM을 호출하는 횟수를 줄입니다. 반복적으로 document.body.all 등이 쓰여야 할 경우 document.body.all 를 다른 변수로 캐싱해둡니다. Array 등에서 array.length 같은 것을 반복문에서 사용해야 할 경우 var len = array.length 등과 같이 array.length 를 캐시해서 사용합니다. 함수 내에서 자주 사용되는 전역함수의 경우 지역 변수로 캐싱해서 사용하는 것이 좋습니다.

 

3. with 키워드의 사용은 피합니다.
JScript 에서의 with 키워드 사용은 scope를 하나 더 정의하는 것과 비슷한 비용이 듭니다.

 

4. 문자열을 많이 다루어야 할 경우에는 배열에 넣고 join 하는게 빠릅니다.
JavaScript에서는 자동으로 효율적인 코드로 변경하지만 JScript는 못합니다. 그래서 이런 식의 StringBuffer를 구현해줘야 빨라집니다.

 

5. eval은 무척이나 비용이 높은 명령입니다.
가급적이면 사용을 피하는게 좋습니다.

 

6. 가능하다면 closure를 피하세요.
closure는 매우 강력하기는 하지만 동시에 매우 위험하기도 합니다. 주의깊게 다루어야 할 뿐더러 최근에 패치가 되기 전까지 JScript는 DOM에 사용된 closure에 대해서 메모리 누수 현상이 있었습니다(패치 되지 않았거나 IE6 미만의 버전을 사용한다면 여전히 존재할 것입니다).

 

7. 프로퍼티 접근 함수는 사용하지 마세요.
객체지향 측면에서는 훌륭하지만 JScript로서는 끔찍합니다(헉… 이거 프레임웍에 썼는데…).


원문보기
IE + JavaScript Performance Recommendations - Part 1
IE+JavaScript Performance Recommendations Part 2: JavaScript Code Inefficiencies
IE+JScript Performance Recommendations Part 3: JavaScript Code Inefficiencies


FROM http://mygony.com/archives/1184

출처 : http://okjsp.tistory.com/1165643139

한국어를 사용하는 우리에게 불필요한 기능 하나가 있습니다. 대표적인 것이 스펠링(spellig) 체크하는 기능이죠. 이것 외에도 이클립스 WTP를 설치하고 기본적으로 설정을 바꿔주는 것이 좋은 것들이 있는데 소개하려 합니다. 이클립스 유로파(3.3) WTP 버전을 기준으로 합니다.

1. 스펠링 체크 안하기

2. 문법검사 파일 범위 줄이기

3. 공백 비교 안하기

4. 이클립스 최대 메모리 확보하기

5. 패키지 익스플로러 트리계층으로 보기

6. Problems 뷰에서 하위 항목만 보기


일단 이 정도를 뽑아봤습니다. 성능에 관련된 것도 있고, 편한 UI 때문에 적어놓은 것도 있습니다.

제가 이클립스를 설치하고 손대는 설정들입니다.


출처 : http://younghoe.info/1232



1. 필수 플러그인 설치

2. 설정 변경
3. 튜닝
  • Heap 메모리 보기 설정: Preferences -> General 에서 Show heap status를 체크
  • GC 줄이기 위한 메모리 설정: eclipse.ini에서 -Xms와 -Xmx 값을 -Xms1000M -Xmx1000M 로 변경
  • 불필요한 플러그인 초기 기동 방지: Preferences -> General -> Startup and Shutdown 에서 디폴트로 선택되는 플러그인 중 불필요한 것 제외 (내 경우는 모두 불필요함)
  • 저장시 Organize Imports 자동 실행: Preferences -> Java -> Editor -> Save Actions에서 Perform the selected actions on save와 Organize imports 를 순서대로 선택
  • 워크스페이스 자동 리프레시 설정: 이클립스 밖에서 워크스페이스 파일 수정한 경우 자동으로 이클립스에서도 인식하게 함. Preferences -> General -> Workspace 에서 Refresh automatically 선택
  • 자바 파일 아이콘을 다양하게: 자바 파일을 펼쳐야 해당 파일이 Class, Interface, Enum 중에 어떤 타입을 정의했나 알 수 있다. Preferences -> General ->Appearance -> Label Decorations 에서 Java Type Indicator를 선택하면, 자바 파일 아이콘이 Class, Interface, Enum 등의 타입 정보가 드러나게 바뀐다.


eclipse.ini 예제

root 폴더 하위의 eclipse.ini 파일의 내용에서 launcher.XXMaxPermSize값(ex. 256M)을 높여서 재설정해준다. 필요 시 메모리 사용 최소값(-Xms)과 최대값(-Xmx)을 증가시켜서 사용하도록 한다. 다음은 Eclipse 3.5.0(Galileo) 버전의 eclipse.ini 파일 예이다.


-clean
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
128m
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms400m
-Xmx512m



showsplash org.eclipse.platform
--launcher.XXMaxPermSize 512m
-vmargs
-Xms40m
-Xmx512m
-XX:MaxPermSize=512m
-Xms40m
-Xmx512m

Xms : 초기 시작할때 차지하는 메모리 크기
Xmx : 최대 사용할 수 있는 메모리 크기
XX:PermSize : 클래스 정보를 저장하는 메모리 크기

출처 : http://www.jakartaproject.com/article/document/119188738462761


제목 : charset 에 대해서...
글쓴이: 손님(guest) 2006/06/06 19:34:47 조회수:651 줄수:13
res.setContentType("text/html;charset=euc-kr")

서블리에서 한글을 사용하기 위한 구문인데요...

charset의 정확한 개념이 뭔가요 ?
물론, 직역하면 문자셋이 되겠네요...


궁금한 것은, euc-kr 외에 다른 chartset을 사용하면 한글을 표현하지 못하는 건지요 ?
charset 자체가 클라이언트 컴퓨터의 OS 와 밀접한 관련이 있을 것 같은데요...


영문 OS 라면 euc-kr 라고 해도 한글 표현이 안 될거 아닌가요 ?


답변 부탁 드려요 ^^
제목 : Re: charset의 의미
글쓴이: 정정식(websphere) 2006/06/15 01:52:44 조회수:1704 줄수:55
정확히 말씀드리려면, 자료를 찾아보고, 답변을 적어야 겠지만, 질문이 critical한 것 같지는 않아
대충 기억을 더듬어 답변을 올립니다. ^^ 혹시 틀린 부분이 있을 지도 모릅니다.


1. charset의 의미
charset = "coded character set"
charset은 "컴퓨터에서 문자를 표현하기 위해, 각 문자를 정수값에 대응시켜 놓은 체계"를 의미합니다.


예를 들어, euc-kr charset이라면, 영숫자와 한글 그리고 일부 특수문자와 한자들을 정수값에 대응해 놓은 것입니다.
euc-kr환경에서 한글을 입력하면, 컴퓨터는 euc-kr charset에서 각 문자별로 지정한 정수값을 쓰게 됩니다.


2. charset이 달라진다면..
각 charset별로, 표현하고자하는 문자와 대응하는 정수값이 달라질 수 있습니다.
예를들어 euc-kr은 태국문자를 위한 정수값을 정의하지 않았으므로, 태국문자는 표현하거나 입력할 수 없습니다.


그리고, euc-kr charset에 맞춰 한글로 어떤 내용을 작성했는데,
이것을 iso-8859-1 charset 환경에서 열어본다면, 한글 대신에 엉뚱한 특수문자쌍들을 보게 될 것입니다.


이런 문제 때문에, 문자 데이터를 주고 받을 때는 서로 간에 charset을 일치시킬 필요가 있습니다. 그렇지
않으면, 원래 생각했는 내용 대신 "깨진 문자들"을 보게 될테니까요.
( 가끔 charset은 일치되었는데, 사용하는 폰트에 대응하는 문자가 없어서 깨져보이는 경우도 있습니다. )


서블릿 코딩시에, content type의 일부로 charset을 명시하는 것은 웹 브라우저에게 사용하는 charset을
알려주어 오해하지 않게 하기 위해서입니다.


3. 한글을 표현할 수 있는 charset
한글을 표현할 수 있도록 설계된 charset은 euc-kr외에도, ksc5601, cp933, cp949 등등 꽤 많습니다.
그리고, 전세계 모든 문자를 표현할 목적으로 설계된 unicode역시 한글을 지원합니다.
그러나, 한글을 지원하는 charset을 사용하더라도, 문서를 만들 때 사용한 charset과 읽을 때 사용하는
charset이 다르다면, 제대로 그 내용을 볼 수 없을 것입니다. 이 경우에는 따로 conversion로직을 사용하여
원하는 charset에 맞춰 데이터를 가공해야 할 것입니다.
( euc-kr, ksc5601 같은 경우는 거의 차이가 없어 호환가능합니다. )


3. 영문 OS에서 한글 표현
charset에 맞추어 문자데이터를 처리하는 것은 OS나 DBMS, 미들웨어 등 플랫폼이므로, 플랫폼에서
제공해주지 않는 charset을 사용할 수는 없습니다.
다행히도, 최근의 플랫폼 SW들은 다양한 charset 지원을 포함하고 있습니다. 만약 어떤 OS가 euc-kr모드로
작동하고 있다면, 설령 영문OS라 하더라도, 한글 처리에 문제가 없다고 볼 수 있습니다.
문제가 있다면 euc-kr모드로 작동하고 있는 것이 아니겠죠.


저 같은 경우, 영문 OS를 설치하고, 그 위에서 한글을 사용해 본 적이 있습니다.


4. encoding
charset과 비슷한 의미로 사용하는 단어로 encoding이 있습니다.
charset이 문자에 대해 정수값을 지정한 것이라면,
encoding은 "문자를 표현하는 정수값을 어떤 bit배열로 표현할 것"인지를 의미합니다.


대부분의 경우, charset과 encoding을 구별할 필요가 없습니다. 왜냐하면 정수값을 bit배열로 표현하는 방법은
하나만 있을테니까요. 그러나 unicode 경우에는 UTF-8, UTF-16 같이 몇 가지 다른 encoding을 사용합니다.
charset이 같다면, 그 charset을 지원하는 어떤 encoding을 사용하든지, 각 문자에 대응하는 논리적인 정수값은 동일합니다.
그러나 실제로 기록되는 bit배열은 encoding에 따라 달라질 수 있습니다. 이 경우, 제대로 데이터를 주고 받으려면, charset뿐 아니라 encoding까지도 맞춰야 합니다.


===========================
재키의 호기심
www.jeongsik.name
===========================


http://www.javaservice.net/~java/bbs/read.cgi?m=devtip&b=servlet&c=r_p&n=1150303964


출처 : http://www.jakartaproject.com/article/jakarta/118827865707684

최근 오라클버젼들은 일반 String처럼 clob을 처리할 수 있지만 그렇지 않은 버젼들은 DBUtils를 조금 수정해 주서야 합니다

resultset의 메타 정보를 이용해서 컬럼 타입이 clob인 넘들만 따로 처리하는 로직입니다

org.apache.commons.dbutils.BasicRowProcessor.java 를 다음과 같이 수정한 후 다시 컴팔 하세요


    private Object createBean(
        ResultSet rs,
        Class type,
        PropertyDescriptor[] props,
        int[] columnToProperty,
        int cols)
        throws SQLException {


        Object bean = this.newInstance(type);       
        Object value = null;
        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i <= cols; i++) {

            if (columnToProperty[i] == PROPERTY_NOT_FOUND) {
                continue;
            }
           
            PropertyDescriptor prop = props[columnToProperty[i]];
            Class propType = prop.getPropertyType();
           
            if ("CLOB".equals(meta.getColumnTypeName(i))) {
                value = readClob(rs, i);
            }
            else {
                value = rs.getObject(i);
            }

            if (propType != null && value == null && propType.isPrimitive()) {
                value = primitiveDefaults.get(propType);
            }
           
            this.callSetter(bean, prop, value);
        }

        return bean;
    }
   
    protected Object readClob(ResultSet rs, int idx) {
        StringBuffer stringbuffer = new StringBuffer();
        char[] charbuffer = new char[1024];
        int read = 0;
       
        Reader reader = null;
        String result = null;
        try {
            reader = rs.getCharacterStream(idx);
            while ((read = reader.read(charbuffer, 0, 1024)) != -1)
                stringbuffer.append(charbuffer, 0, read);

            result = stringbuffer.toString();
        } catch (Exception exception) {
            System.out.println(exception);
        } finally {
            if (reader != null) try { reader.close(); } catch (Exception e){}
        }

        return result;
    }



출처 : http://www.jakartaproject.com/article/jakarta/117730447142917

Commons-Fileupload 1.2


1.2 버젼이 2007.2.13에 새롭게배포되었습니다

1.1 이하단계 버젼과 달라진 점을 알아보도록 하지요

 

I. commons-fileupload 1.1

http://www.jakartaproject.com/article/jakarta/110887666654000

 

 

II. 다운로드 및 설치

 -. fileupload는 commons의 io가 필요합니다

commons-fileupload

http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi

commons-io

http://jakarta.apache.org/site/downloads/downloads_commons-io.cgi



III. 달라진점

 -. DiskFileUpload 가 Deprecated 되었습니다

 -. 리스너 추가를 통해 업로드 진행 상태를 파악할 수 있습니다(대용량 파일인 경우 유용)

 -. 비정상적인 업로드시 나타나는 중간 쓰레기 파일들을 제거할 수 있습니다

 

IV. 예제소스코드


upload.html

<form name=fileupload method=post action=./upload enctype="multipart/form-data">
 file : <input type=file name=file1><br>
 text : <input type=text name=text1><br>
 <input type=submit name=button1 value=submit>
</form>

web.xml

가비지 파일 cleaner에 사용되는 FileCleanerCleanup을 listener로 추가

샘플 코드에서 사용되는 서블릿 등록

<web-app>

   ...

 

   <listener>
       <listener-class>
           org.apache.commons.fileupload.servlet.FileCleanerCleanup
       </listener-class>
   </listener>


    ...


    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>UploadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    ...

</web-app>


UploadServlet.java


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadServlet extends HttpServlet {
   
    String upload_dir = null;
    public void init(ServletConfig config) throws ServletException {
          super.init(config); 
          upload_dir = config.getServletContext().getRealPath("/upload/");
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   

        // form type이 multipart/form-data 면 true 그렇지 않으면 false를 반환
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       
        if (isMultipart) {
            try {

                int yourMaxMemorySize = 1024 * 10;                 // threshold  값 설정
                long yourMaxRequestSize = 1024 * 1024 * 100;   //업로드 최대 사이즈 설정 (100M)

                File yourTempDirectory = new File(upload_dir);
               
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(yourMaxMemorySize);
                factory.setRepository(yourTempDirectory);               
   
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(yourMaxRequestSize);          // 임시 업로드 디렉토리 설정
                upload.setHeaderEncoding("EUC_KR");               // 인코딩 설정
               

                /**

                 *  업로드 진행 상태 출력 (Watching progress)

                */
                ProgressListener progressListener = new ProgressListener(){
                   private long megaBytes = -1;
                   public void update(long pBytesRead, long pContentLength, int pItems) {
                       long mBytes = pBytesRead / 1000000;
                       if (megaBytes == mBytes) {
                           return;
                       }
                       megaBytes = mBytes;
                       System.out.println("We are currently reading item " + pItems);
                       if (pContentLength == -1) {
                           System.out.println("So far, " + pBytesRead + " bytes have been read.");
                       } else {
                           System.out.println("So far, " + pBytesRead + " of " + pContentLength
                                              + " bytes have been read.");
                       }
                   }
                };
                upload.setProgressListener(progressListener);   // 진행상태 리스너 추가
   

                String fieldName = null;
                String fieldValue = null;
                String fileName = null;
                String contentType = null;
                long sizeInBytes = 0;

                List items = upload.parseRequest(request);               
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
   

                    // 정상적인 폼값 출력 및 처리
                    if (item.isFormField()) {
                        fieldName = item.getFieldName();
                        fieldValue = item.getString();
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("Field Value : "+fieldValue);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                       

                    // 업로드 파일 처리
                    } else {
                        fieldName = item.getFieldName();
                        fileName = item.getName();
                        contentType = item.getContentType();
                        sizeInBytes = item.getSize();
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("File Name : "+fileName);
                        System.out.println("ContentType : "+contentType);
                        System.out.println("File Size : "+sizeInBytes);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");

                        String savefile = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length());
                        File uploadedFile = new File(upload_dir+"\\"+savefile);
                        item.write(uploadedFile);
                    }
                }


            // 설정한 업로드 사이즈 초과시 exception 처리
            } catch (SizeLimitExceededException e) {
                e.printStackTrace();   

            // 업로드시 io등 이상 exception 처리
            } catch (FileUploadException e) {
                e.printStackTrace();

            // 기타 exception 처리
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }   
}


V. 실행결과

-----+-----+-----+-----+-----+-----+-----+-----+-----
Field Name : file1
File Name : C:\Program Backup\AromNet11a\AromNet.exe
ContentType : application/octet-stream
File Size : 274432
-----+-----+-----+-----+-----+-----+-----+-----+-----
-----+-----+-----+-----+-----+-----+-----+-----+-----
Field Name : text1
Field Value : this is test
-----+-----+-----+-----+-----+-----+-----+-----+-----

큰 파일을 업로드한 경우 업로드 상태 출력

We are currently reading item 0
So far, 4096 of 338043623 bytes have been read.
We are currently reading item 1
So far, 1003477 of 338043623 bytes have been read.
We are currently reading item 1
So far, 2002901 of 338043623 bytes have been read.
We are currently reading item 1
So far, 3002325 of 338043623 bytes have been read.
We are currently reading item 1
So far, 4001749 of 338043623 bytes have been read.
We are currently reading item 1
So far, 5001173 of 338043623 bytes have been read.
We are currently reading item 1
So far, 6000597 of 338043623 bytes have been read.
We are currently reading item 1
So far, 7000021 of 338043623 bytes have been read.
We are currently reading item 1
So far, 8003498 of 338043623 bytes have been read.
We are currently reading item 1
So far, 9002922 of 338043623 bytes have been read.
We are currently reading item 1
So far, 10002346 of 338043623 bytes have been read.
We are currently reading item 1
So far, 11001770 of 338043623 bytes have been read.
We are currently reading item 1
So far, 12001194 of 338043623 bytes have been read.
We are currently reading item 1
So far, 13000618 of 338043623 bytes have been read.
We are currently reading item 1
So far, 14000042 of 338043623 bytes have been read.
We are currently reading item 1
So far, 15003605 of 338043623 bytes have been read.
We are currently reading item 1
So far, 16003029 of 338043623 bytes have been read.

...


=============================================

본문서는 자유롭게 배포/복사 할수 있지만

이문서의 저자에 대한 언급을 삭제하시면 안됩니다

저자 : GoodBug (unicorn@jakartaproject.com)

최초 : http://www.jakartaproject.com 

=============================================

출처 : http://www.jakartaproject.com/article/data/117521573669532

jad -o -r -sjava -d디컴파일될타겟디렉토리 클래스파일소스디렉토리/**/*.class

예) jad -o -r -sjava -src unicorn/**/*.class



This is README file for Jad - the fast Java Decompiler.
Jad home page: http://www.kpdus.com/jad.html
Copyright 2001 Pavel Kouznetsov (jad@kpdus.com).

0. Please read the disclaimer on the Jad home page.

1. Installation.

Unzip jad.zip file into any appropriate directory on your hard drive.
This will create two files:

    - an executable file named 'jad.exe' (Windows *)
      or 'jad' (*n*x)

    - this README file

No other setup is required.

2. How to use Jad

To decompile a single JAVA class file 'example1.class'
type the following:

     jad example1.class

This command creates file 'example1.jad' in the current directory.
If such file already exists Jad asks whether you want to overwrite it or not.
Option -o permits overwriting without a confirmation.

You can omit .class extension and/or use wildcards in the names of
input files.

Option -s <ext> allows to change output file extension:

     jad -sjava example1.class

This command creates file 'example1.java'. Be careful when using
options -o and -sjava together, because Jad can accidentally overwrite
your own source files.

Jad uses JAVA class name as an output file name. For example, if class
file 'example1.class' contains JAVA class 'test1' then Jad will create
file 'test1.jad' rather than 'example1.jad'. If you want to specify
your own output file name use the output redirection:

   jad -p example1.class > myexm1.java

Option -d allows you to specify another directory for output files,
which are created, by default, in the current directory. For example:

   jad -o -dtest -sjava *.class

   (or jad -o -d test -s java *.class, which has the same effect)

This command decompiles all .class files in the current directory
and places all output files with extension .java into directory 'test'.


If you want to decompile the whole tree of JAVA classes,
use the following command:

   jad -o -r -sjava -dsrc tree/**/*.class

This command decompiles all .class files located in all
subdirectories of 'tree' and creates output files in subdirectories
of 'src' according to package names of classes. For example, if file
'tree/a/b/c.class' contains class 'c' from package 'a.b', then
output file will have a name 'src/a/b/c.java'.

Note the use of the "two stars" wildcard ('**') in the previous
command. It is handled by Jad rather than the command shell, so on
UNIX the last argument should be single-quoted:

   jad -o -r -sjava -dsrc 'tree/**/*.class'


In a case you want to check the accuracy of the decompilation or just
curious, there is an option -a which tells Jad to annotate the output
with JAVA Virtual Machine bytecodes.

Jad supports the inner and anonymous classes.
When Jad expands wildcards in the input file names,
it automatically skips matching inner classes.
On UNIX Jad skips inner classes if there is more than
one class specified in the command line.
Jad looks for inner classes in the directory of their top-level
container class.

3. List of the command-line options.

Jad accepts the following options:

   -a       - annotate the output with JVM bytecodes (default: off)
   -af      - same as -a, but output fully qualified names when annotating
   -clear   - clear all prefixes, including the default ones (can be abbreviated as -cl)
   -b       - output redundant braces (e.g., if(a) { b(); }, default: off)
   -d <dir> - directory for output files (will be created when necessary)
   -dead    - try to decompile dead parts of code (if any) (default: off)
   -disass  - disassemble method bytecodes (no JAVA source generated)
   -f       - output fully qualified names for classes/fields/methods (default: off)
   -ff      - output class fields before methods (default: after methods)
   -i       - output default initializers for all non-final fields
   -l<num>  - split strings into pieces of maximum <num> chars (default: off)
   -lnc     - annotate the output with line numbers (default: off)
   -lradix<num> - display long integers using the specified radix (8, 10 or 16)
   -nl      - split strings on newline character (default: off)
   -nocast  - don't generate auxiliary casts
   -nocode  - don't generate the source code for methods
   -noconv  - don't convert Java identifiers (default: convert)
   -noctor  - suppress the empty constructors
   -nodos   - do not check for class files written in DOS mode (CR before NL, default: check)
   -nofd    - don't disambiguate fields with the same names by adding signatures to their names (default: do)
   -noinner - turn off the support of inner classes (default: on)
   -nolvt   - ignore Local Variable Table information
   -nonlb   - don't output a newline before opening brace (default: do)
   -o       - overwrite output files without confirmation (default: off)
   -p       - send decompiled code to STDOUT (e.g., for piping)
   -pi<num> - pack imports into one line after <num> imports (default: 3)
   -pv<num> - pack fields with identical types into one line (default: off)
   -pa <pfx>- prefix for all packages in generated source files
   -pc <pfx>- prefix for classes with numerical names (default: _cls)
   -pf <pfx>- prefix for fields with numerical names (default: _fld)
   -pe <pfx>- prefix for unused exception names (default: _ex)
   -pl <pfx>- prefix for locals with numerical names (default: _lcl)
   -pm <pfx>- prefix for methods with numerical names (default: _mth)
   -pp <pfx>- prefix for method parms with numerical names (default: _prm)
   -r       - restore package directory structrure
   -radix<num> - display integers using the specified radix (8, 10 or 16)
   -s <ext> - output file extension (by default '.jad')
   -safe    - generate additional casts to disambiguate methods/fields (default: off)
   -space   - output space between keyword (if/for/while/etc) and expression (default: off)
   -stat    - display the total number of processed classes/methods/fields
   -t       - use tabs instead of spaces for indentation
   -t<num>  - use <num> spaces for indentation (default: 4)
   -v       - display method names being decompiled
   -8       - convert UNICODE strings into 8-bit strings
              using the current ANSI code page (Win32 only)
   -&       - redirect STDERR to STDOUT (Win32 only)

All single-word options have three formats:

  -o    - 'reverses' value of an option
  -o+   - set value to 'true' or 'on'
  -o-   - set value to 'false' or 'off'

You can specify the options you want to be set by default in the environment variable
JAD_OPTIONS. For example:

JAD_OPTIONS=-ff+ -nonlb+ -t+ -space+

출처 : http://www.okjsp.pe.kr/seq/98774

이놈에 CLOB라는게...

어떻게 WAS별로 설정이 조금씩 틀리군요..

정확히는..WAS별로 틀린게 아니라..WAS별로 datasource 설정이

틀려서 그런듯한데...

할때마다 CLOB 검색법 찾아서 하기도 지쳤습니다.

한번 정리 해봤습니다..

(중복이면 난감;; 개인적인 백업 목적도 있으니 중복이라도 야단치지 마세요;;)


import java.sql.Clob;
import weblogic.jdbc.common.OracleClob;
import oracle.jdbc.driver.OracleResultSet;
import oracle.sql.CLOB;
import org.apache.commons.dbcp.DelegatingResultSet;


String query1 = "select content from "+table+" where no="+ no + " for update";

con = getConnection();
con.setAutoCommit(false);//꼭 setAutoCommit을 false로 지정

pstmt = con.prepareStatement(query1);
rs = pstmt.executeQuery();

while (rs.next()){

 /**********************************************
 * Tomcat
 * ********************************************/
 Clob clob = rs.getClob(1);
 Writer writer = ((CLOB)clob).getCharacterOutputStream();
 Reader src = new CharArrayReader(contentData.toCharArray());
 char[] buffer = new char[1024];
 int read = 0;
 while ( (read = src.read(buffer,0,1024)) != -1)
 {
   writer.write(buffer, 0, read); // write clob.
 }
 src.close();               
 writer.close();   


 /**********************************************
 * weblogic
 * ********************************************/
 Clob clob = rs.getClob(1);
 Writer writer = ((OracleClob)clob).getCharacterOutputStream();
 Reader src = new CharArrayReader(contentData.toCharArray());
 char[] buffer = new char[1024];
 int read = 0;
 while ( (read = src.read(buffer,0,1024)) != -1)
 {
   writer.write(buffer, 0, read); // write clob.
 }
 src.close();               
 writer.close();


 /**********************************************
 * sunone
 * ********************************************/
 Clob clob = rs.getClob(1);
 Writer characterStream = clob.setCharacterStream(0);
 characterStream.write(contentData);
 characterStream.close();


 /**********************************************
 * interstage

 * ********************************************/

 CLOB clob = ((OracleResultSet)((DelegatingResultSet)rs).getDelegate()).getCLOB(1);
 BufferedWriter writer = new BufferedWriter(clob.getCharacterOutputStream());
 writer.write(form.getContent());
 writer.close();

}

con.commit();
con.setAutoCommit(true);

+ Recent posts