달력

5

« 2024/5 »

  • 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
2012. 7. 20. 15:36

1 Tomcat 2 Service Enjoy/JSP2012. 7. 20. 15:36



두개의 Tomcat을 설치하여 server.xml의 포트 부분을 변경하는 방법도 있지만 

너무 번거러운 관계로 server.xml에서 service 부분만 추가하여 포트를 변경하는 방법이다.


<Service name="Catalina">

    <Connector 

        port="8080"

        redirectPort="8443"

        minSpareThreads="25"

        connectionTimeout="20000"

        maxThreads="500"

        maxSpareThreads="75">

    </Connector>

    <Connector

        port="8009"

        redirectPort="8443"

        protocol="AJP/1.3">

    </Connector>

    <Engine

        defaultHost="localhost"

        name="Catalina">

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>

      <Host

          appBase="webapps"

          name="localhost">

       <!-- 아래의 Context 부분은 Tomcat 버전에 따라 따로 설정할 수 있다. -->

       <!--<Context path="/test" docBase="C:\text" debug="0" reloadable="true"/>-->

      </Host>

    </Engine>

  </Service>



  <Service name="Catalina2">

    <Connector

        port="8081"

        redirectPort="8444"

        minSpareThreads="25"

        connectionTimeout="20000"

        maxThreads="500"

        maxSpareThreads="75">

    </Connector>

    <Connector

        port="8010"

        redirectPort="8444"

        protocol="AJP/1.3">

    </Connector>

    <Engine

        defaultHost="localhost"

        name="Catalina2">

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>

      <Host

          appBase="webapps"

          name="localhost">

       <!-- 아래의 Context 부분은 Tomcat 버전에 따라 따로 설정할 수 있다. -->

       <!--<Context path="/test" docBase="C:\text" debug="0" reloadable="true"/>-->

       </Host>

    </Engine>

  </Service>


:
Posted by 라면스프
2012. 7. 20. 15:12

Java Stored Procedure 예제 Enjoy/JAVA2012. 7. 20. 15:12

출처 : http://do3ng.wordpress.com/2007/08/13/java-stored-procedure-%EB%A7%8C%EB%93%A4%EA%B8%B0/



Java Stored Procedure 예제

 

  Java Stored Procedure는 웹 개발시 배치잡(Batch Job) 형태의 작업이나, 많은 데이터의 작업이 필요한 경우 뛰어난 성능 향상을 가져 올 수 있습니다. 또한 PL/SQL로 구현하기 어려우나 Java로 구현이 편리할 경우(예를 들어 OS 파일 핸들링, 암호화..) 사용하면 성능 향상과 동시에 편리하게 사용 할 수 있다.

 

  생성 방법 요약

  1) Writing the JAva Classes

- JAVA 소스생성

  2) Load and Resolve the Java Classes

- loadjava를 이용하여 class를 DB에 Load

  3) Publish the Java Classes

- load된 자바클래스를 이용하여 오라클 프로시저/함수 만들기

  4) Call the Stored Procedure or Function

- 프로시저 또는 함수를 사용

 

  아래 예저는 OS 파일을 읽고, 이름을 변경할 수 있는 Java Stored Procedure 예제입니다.  PL/SQL에서 OS상의 파일에 대한 작업을 하려면 UTL_FILE패키지 이용 할 수 있지만 많은 불편함이 있습니다. Java Stored Procedure를 사용해서 작업하는 예제입니다.

 

① JAVA 소스생성

package com.oracleclub.odd.jsp;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

public class FileUtil {

    /**

     *파일을 읽어서 String으로 반환<br/>

     *@param fileDir  파일 경로와 파일명 String

     *@return 파일 데이터 byte[]

     */

    public static String readFile(String fileDir) {

        byte[] bytes = null;

        String data = "";

        try{

            FileInputStream fis = new FileInputStream(fileDir);

            bytes = new byte[fis.available()];

            fis.read(bytes);

            fis.close();

            data = new String(bytes);

        } catch(IOException ioe){

            System.out.println(" FileUtil.readFile error : "+ioe.getMessage());

        } finally {

        }

        return data;

    }

   

    /**

     *oldFileName을 newFileName 파일명으로 변경.<br/>

     *@param oldFileName String

     *@param newFileName String

     *@return boolean

     */

    public static void renameFile(String oldFileName, String newFileName) {

        try{

            if (File.separatorChar != ‘/’) {

                oldFileName = oldFileName.replace(File.separatorChar, ‘/’);

                newFileName = newFileName.replace(File.separatorChar, ‘/’);

            }

            File oldFile = new File(oldFileName);

            File newFile = new File(newFileName);

            if(!oldFile.exists())

                System.out.println("FileHndr.renameFile() Not Exist Source File : "+ oldFile);

            else

                oldFile.renameTo(newFile);

                System.out.println("파일명이 변경 되었습니다 ?>"+newFile);

        } catch(Exception e){

            System.out.println(" FileUtil.renameFile error : "+e.getMessage());

        }

    }

}

② loadjava를 이용하여 class를 DB에 Load

 E:\class directory>loadjava -u scott/tiger -v FileUtil.class

  -v : verbose모드 옵션

  -u : oracle 사용자

  -resolve : .class파일이 아닌 .java파일을 지정할때 컴파일 함

? 정상적으로 생성되었는지 확인

C:\>SQLPLUS scott/tiger

SQL>SELECT object_name

        FROM USER_OBJECTS

        WHERE object_type=’JAVA CLASS’;

③ load된 자바클래스를 이용하여 오라클 프로시저/함수 만들기

? 파일을 읽어 출력하는 함수 (Java 메소드에서 Return 값이 있으면 함수로 생성)

? NAME 키워드 뒤에 패키지.클래스.메소드 명을 입력 합니다.

CREATE OR REPLACE FUNCTION read_file(fileName VARCHAR2)

    RETURN VARCHAR2

    AS

    LANGUAGE JAVA

    NAME ‘com.oracleclub.odd.jsp.FileUtil.readFile(java.lang.String) return java.lang.String’;

/

? 파일명을 변경하는 프로시저 (Java 메소드에서 Return 값이 없으면 프로시저로 생성)

CREATE OR REPLACE PROCEDURE rename_file(oldName VARCHAR2, newName VARCHAR2)

    AS

    LANGUAGE JAVA

    NAME ‘com.oracleclub.odd.jsp.FileUtil.renameFile(java.lang.String, java.lang.String)’;

/

? 패키지로 생성해서 사용 할 수도 있습니다.

CREATE OR REPLACE PACKAGE file_util IS

    FUNCTION  read_file(fileName VARCHAR2) RETURN VARCHAR2;

    PROCEDURE rename_file(oldName VARCHAR2, newName VARCHAR2);

END file_util;

/

CREATE OR REPLACE PACKAGE BODY file_util IS

    FUNCTION read_file(fileName VARCHAR2) RETURN VARCHAR2

    AS

    LANGUAGE JAVA

    NAME ‘com.oracleclub.odd.jsp.FileUtil.readFile(java.lang.String) return java.lang.String’;

    PROCEDURE rename_file(oldName VARCHAR2, newName VARCHAR2)

    AS

    LANGUAGE JAVA

    NAME ‘com.oracleclub.odd.jsp.FileUtil.renameFile(java.lang.String, java.lang.String)’;

END file_util;

/

④ 프로시저 또는 함수를 사용.

? 파일을 읽고 쓸 수 있는 권한을 부여하기 위해 SYS 유저로 접속

SQL>CONN / AS SYSDBA

? 권한을 부여하지 않으면 "ERROR! Handling File: the Permission" 에러가 발생한다.

SQL> EXEC DBMS_JAVA.GRANT_PERMISSION( ‘SCOTT’, ‘SYS:java.io.FilePermission’,'<<ALL FILES>>’, ‘read ,write, execute, delete’ );

SQL> CONN SCOTT/TIGER

SQL> SET SERVEROUTPUT ON

? 자바출력은 트레이스파일로 쓰여지므로, 출력을 화면에 표시하도록 변경후 프로시저 호출

SQL> CALL DBMS_JAVA.SET_OUTPUT(1000);

 

? 파일을 읽는 함수 호출

SQL> SELECT READ_FILE(‘E:/test.txt’) FROM DUAL;

READ_FILE(‘E:/TEST.TXT’)

??????????????-

2006년 8월 26일 Oracle Developer Day

 

? 파일명을 바꾸는 프로시저 호출

SQL> EXEC RENAME_FILE(‘E:/test.txt’, ‘E:/new.txt’);

파일명이 변경 되었습니다 ?>E:\new.txt

PL/SQL 처리가 정상적으로 완료되었습니다.

?> 파일 이름이 변경되었는지 확인

 

? 바낀 파일을 패키지로 읽어 보겠습니다.

SQL> SELECT FILE_UTIL.READ_FILE(‘E:/new.txt’) FROM DUAL;

FILE_UTIL.READ_FILE(‘E:/NEW.TXT’)

????????????-

2006년 8월 26일 Oracle Developer Day

:
Posted by 라면스프

출처 : http://gurucode.egloos.com/1452887


OS: Microsoft Windows 2000 [Version 5.00.2195]

DBMS: Oracle9i Enterprise Edition Release 9.2.0.4.0 - Production

작성자: 강명규

작성일: 2004-04-17


이 글은 Oracle and Java Stored Porcedures(www.developer.com/db/article.php/3337411)을 정리한 것임.

이 글에 나오는 예제또한 약간의 첨삭이 있지만, 원문에 충실히 할 것임.


오라클에서 stored procedure/function은 전통적으로 PL/SQL로 작성했었다.

사실, Native언어(C언어등 OS상에서 실행파일을 얻는)나 자바로도 가능하다.

특이하게 자바의 경우 오라클에서 VM을 제공하므로 별다른 복잡한 절자없이

PL/SQL처럼 손쉽게 스토어드 프로시저나 함수를 생성할 수 있다.


그럼, 왜 PL/SQL이 있는데 또 다른 언어를 지원하려는 것일까?

네이티브코드는 성능에 잇점이 있을 수 있다.

몇몇 글을 보면 네이티브코드의 경우, 오라클에 존재하는 PL/SQL로 작성된 패키지들을 전체를

네이티브코드로 변경해야 성능상의 이점을 볼 수 있다고 한다. PL/SQL과 섞어쓰면 성능이

오히려 떨어진다고 한다.


그럼 자바는?

실체 성능적인 부분을 측정해보지는 않았는데 PL/SQL과 혼합해서 써도 무방하다고 한다.


자바를 사용하면 좋은 점은?

어느 정도 데이터베이스와 독립적

PL/SQL을 별도로 배울 필요가 없음

개발팀에서 PL/SQL보다는 자바를 더 능숙하게 다루는 팀원이 많을 경우가 대개일 것임.


자바를 사용하면 찝찝한 점은?

성능이 아무래도 pl/sql로 작성한 것보다는 떨어진다.

오라클 SGA에 자바를 위한 메모리를 할당해줘야 한다.

즉, 성능과 리소스를 더 필요로 한다는 의미.


필자의 생각은?

PL/SQL로 작성하던 놈이라 별다른 것이 없다면 PL/SQL로 작성하고,

PL/SQL로 작성하기 어려우면 JAVA를 고려하는 것이 좋겠다.



들리는 소문에 의하면, 차후 오라클버전에서 PL/SQL을 없애고 자바로 대체한다는

믿거나 말거나 하는 얘기가 떠돈다. 사실 오라클사에서는 현재 PL/SQL은 현상유지 차원에서

계속 지원할 것이라고 하나, 자바쪽으로 비중이 옮겨가는 것은 사실인 것 같다.


결론은?

오라클 8i부터 자바로 stored procedure/function를 사용할 수 있다.

원래 pl/sql을 사용하던 사람은 계속 pl/sql을 쓰고, 처음하는 사람은 자바를 사용하도록 하자.

아무래도 둘이 섞어쓰면 찜찜할 것 같긴하다.

실제 자바소스가 변경되어, 오라클로 reload한후, 호출명세를 다시 설정해주지 않았더니 오라클이 맛가는 현상을 겪었다.

alter system kill session '';으로 어떻게 해보려고 했으나 감감 무소식.. shutdown abort밖에 없었다.



자, 이제 직관적으로 간단명료하게 진행하겠다.

우선 오라클에 테스트용 테이블을 생성한다.

SQL> create table test(id int, name varchar(10), salary float);


테이블이 생성되었습니다.


자바로 로직을 작성하고, loadjava를 이용하여 DB에 집어넣는다.

윈도   c:\oracle\ora92\bin\loadjava.bat

유닉스

[sky@gw1 sky]$ file $ORACLE_HOME/bin/loadjava

/u01/app/oracle/product/9.2.0/bin/loadjava: Bourne shell script text executable



[develope/load class]

D:\temp>type TestDML.java

import java.sql.*;

import oracle.jdbc.*;


public class TestDML

{

        // 리턴값이 없으면 오라클 Stored Procedure

        public static void addPerson(int id, String name, float salary)

        {

                System.out.println("새로운 사용자 등록");


                try

                {

                        Connection conn = DriverManager.getConnection("jdbc:default:connection:");

                        String sql = "insert into test values (?,?,?)";

                        PreparedStatement pstmt = conn.prepareStatement(sql);

                        pstmt.setInt(1,id);

                        pstmt.setString(2,name);

                        pstmt.setFloat(3,salary);

                        pstmt.executeUpdate();

                        pstmt.close();

                }

                catch(SQLException e)

                {

                        System.err.println("ERROR! Adding Employee: " + e.getMessage());

                }

        }


        // 리턴값이 있으면 오라클 Function

        public static float getSalary(int id)

        {

                float salary = 0;

                System.out.println(id + "의 급여");


                try

                {

                        ResultSet rs;

                        Connection conn = DriverManager.getConnection("jdbc:default:connection:");

                        String sql = "select salary from test where id=?";

                        PreparedStatement pstmt = conn.prepareStatement(sql);

                        pstmt.setInt(1,id);

                        rs = pstmt.executeQuery();


                        rs.next();

                        salary = rs.getFloat(1);


                        rs.close();

                        pstmt.close();

                }

                catch(SQLException e)

                {

                        System.err.println("ERROR! Adding Employee: " + e.getMessage());

                }


                return salary;

        }

}


-u : DB계정

-v : verbose feedback

-resolve : .class파일이 아닌 .java파일이므로 컴파일해주라.

D:\temp>loadjava -u kang/xxxxxx -v -resolve TestDML.java

arguments: '-u' 'kang/xxxxxx' '-v' '-resolve' 'TestDML.java'

created  : JAVA$CLASS$MD5$TABLE

creating : source TestDML

created  : CREATE$JAVA$LOB$TABLE

loading  : source TestDML

creating : TestDML

resolving: source TestDML


오라클 kang계정을 보면, 뭔가 생성된 것이 보일 것이다.

SQL> select * from tab;


TNAME                          TABTYPE  CLUSTERID

------------------------------ ------- ----------

CREATE$JAVA$LOB$TABLE          TABLE

JAVA$CLASS$MD5$TABLE           TABLE

JAVA$OPTIONS                   TABLE

TEST                           TABLE


SQL> select object_name, object_type, status from user_objects

  2  where object_name='TestDML';


OBJECT_NAME     OBJECT_TYPE        STATUS

--------------- ------------------ -------

TestDML         JAVA CLASS         VALID

TestDML         JAVA SOURCE        VALID


SQL>


위에서 status필드가 VALID가 아니라면 user_errors를 조회해보라.

loadjava는 .sqlj .properties .ser .jar .zip을 인식한다.

만일, kang계정이외에 maddog계정도 이 놈을 사용하겠다고 하면 다음과 같이 한다.


D:\temp>loadjava -u kang/xxxxxx -resolve -resolver "((* KANG)(* MADDOG)(* PUBLIC))" TestDML.java




[publising classes]

SQL이나 PL/SQL에서 자바로 생성한 클래스파일을 호출하려면 publish를 해야 하는데,

자바 클래스는 호출명세(call specification, call spec 혹은 PL/SQL wrapper이라고 불리기도 함)

를 생성/컴파일함으로써 publish될 수 있다.

호출명세는 자바 메소드의 인자와 리턴형을 오라클 SQL타입과 매핑하는 역활을 한다.


SQL> create or replace procedure add_person(id number, name varchar2, salary number)

  2  as language java

  3  name 'TestDML.addPerson(int, java.lang.String, float)';

  4  /


프로시저가 생성되었습니다.


SQL> create or replace function get_salary(id number) return number 

  2  as language java

  3  name 'TestDML.getSalary(int) return int';

  4  /


함수가 생성되었습니다.



즉, 우리는 이제부터 add_person프로시저와 get_salary함수를 사용하면 되는 것이다.

자바출력은 트레이스파일로 쓰여지므로, 출력을 화면에 표시하도록 변경후 프로시저 호출

SQL> set serveroutput on

SQL> call dbms_java.set_output(2000);


호출이 완료되었습니다.


SQL> exec add_person(1,'강명규', 3000.01);

새로운 사용자 등록


PL/SQL 처리가 정상적으로 완료되었습니다.


SQL> select get_salary(1) from dual;


GET_SALARY(1)

-------------

      3000.01


함수는 다음과 같이 해도 된다.

SQL> var salary number;

SQL> call get_salary(1) into :salary;

1의 급여


호출이 완료되었습니다.


SQL> print salary;


    SALARY

----------

   3000.01



자바에서 PL/SQL을 호출하는 방법

CallableStatement cstmt = conn.prepareCall("{my_plsql_porc}");




[Usage Scenario]

오라클에서 OS상의 파일에 대한 작업을 하려면 UTL_FILE패키지를 이용해야 한다.

이것은 OS상의 파일에 접근할 수 있는 인터페이스를 제공하지만 여러가지로 불편하다.

이 경우 자바의 File I/O를 이용하면 더 효율적으로 작업할 수 있을 것이다.



D:\temp>type FileTest.java

import java.io.*;


class FileTest

{

        public static String readFile(String usrFile)

        {

                String fileStr = new String();

                String tmpStr = new String();

                try

                {

                        File file = new File(usrFile);

                        FileReader fr = new FileReader(usrFile);

                        LineNumberReader lnr = new LineNumberReader(fr);


                        do{

                                tmpStr = lnr.readLine();

                                fileStr += tmpStr;

                        } while(tmpStr != null);


                        lnr.close();

                        fr.close();


                }

                catch(Exception e)

                {

                        System.err.println("ERROR! Handling File: " + e.getMessage());

                }


                return fileStr;

        }

}



D:\temp>loadjava -u kang/xxxxxx -v -resolve FileTest.java

arguments: '-u' 'kang/xxxxxx' '-v' '-resolve' 'FileTest.java'

creating : source FileTest

loading  : source FileTest

creating : FileTest

resolving: source FileTest



SQL> create or replace package my_java_utils is

  2  function read_file(file varchar2) return varchar2;

  3  end my_java_utils

  4  ;

  5  /


패키지가 생성되었습니다.


SQL> create or replace package body my_java_utils is

  2  function read_file(file varchar2) return varchar2

  3  as language java

  4  name 'FileTest.readFile(java.lang.String) return java.lang.String';

  5  end my_java_utils;

  6  /


패키지 본문이 생성되었습니다.


SQL>



D:\temp>type hello

안녕!

나는 강명규라고 해!



SQL> conn system/xxxxxx

연결되었습니다.

SQL> exec dbms_java.grant_permission( 'KANG', 'SYS:java.io.FilePermission','d:\temp\hello', 'read' );


PL/SQL 처리가 정상적으로 완료되었습니다.


SQL> conn kang/xxxxxx

연결되었습니다.

SQL> set serveroutput on

SQL> call dbms_java.set_output(2000);


호출이 완료되었습니다.

SQL> select my_java_utils.read_file('d:\temp\hello') from dual;


MY_JAVA_UTILS.READ_FILE('D:\TEMP\HELLO')

--------------------------------------------------------------------------------

안녕!나는 강명규라고 해!null


SQL>


사실 위에서는 hello라는 파일로 했지만, alert.log파일에 대한 처리로 하면 좀 더 현실적일 것이다.



[작업한 내용 제거]

SQL> conn system/xxxxxx

SQL> exec dbms_java.revoke_permission( 'KANG', 'SYS:java.io.FilePermission','d:\temp\hello', 'read');


PL/SQL 처리가 정상적으로 완료되었습니다.


SQL> connect kang/xxxxxx

연결되었습니다.

SQL> drop package my_java_utils;


패키지가 삭제되었습니다.


SQL> drop function get_salary;


함수가 삭제되었습니다.


SQL> drop procedure add_person;


프로시저가 삭제되었습니다.


D:\temp>dropjava -u kang/xxxxxx TestDML FileTest




This article comes from dbakorea.pe.kr (Leave this line as is)


:
Posted by 라면스프
2012. 7. 6. 09:18

oracle 정보 2012. 7. 6. 09:18

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 7. 4. 15:52

eclipse Ganymede 64bit Enjoy/JAVA2012. 7. 4. 15:52




This build requires a 64-bit JVM, and will not run with a 32-bit JVM.

You can, for example, use the Sun 64-bit 1.5 JVM for AMD64.  Note

that the Sun 1.4.2 JVM for AMD64 is 32-bit and therefore cannot be

used to run this build.


http://archive.eclipse.org/eclipse/downloads/drops/R-3.4.2-200902111700/download.php?dropFile=eclipse-SDK-3.4.2-win32-x86_64.zip

:
Posted by 라면스프

출처 : http://active.tutsplus.com/tutorials/flex/using-as3xls-with-the-flex-framework-excel-import/






This tutorial will cover implementation of the AS3XLS ActionScript 3.0 library for the Flex framework. We will demonstrate loading an Excel .xls file into Flash and parsing the data into a Flex datagrid. 

 
:
Posted by 라면스프
출처 : http://www.ibm.com/developerworks/kr/library/os-javapdf/index.html


자바 애플리케이션에서 동적으로 PDF 파일 생성하기


많은 애플리케이션들이 PDF 문서의 동적 생성을 요구하고 있다. 이 같은 애플리케이션은 이메일 전달용 고객 일람표를 생성하는 은행부터, 책의 특정 챕터를 구매하여 이를 PDF 포맷으로 받는 리더기 까지 다양하다. 그 리스트는 끝이 없다. 이 글에서 iText 자바 라이브러리를 사용하여 PDF 문서를 만들 것이다. 여러분의 이해를 돕기 위해 샘플 애플리케이션도 제공한다.

iText와 친해지기

iText는 Lowagie.com(참고자료)에서 무료로 사용할 수 있는 자바 라이브러리이다. iText 라이브러리는 강력하고, HTML, RTF, XML 문서의 생성 뿐만 아니라 PDF 생성을 지원한다. 문서에 사용될 다양한 폰트를 선택할 수 있다. 또한 iText 구조에서는 같은 코드를 사용하여 앞서 언급한 유형의 문서를 만들 수 있다.

iText 라이브러리에는 다양한 폰트로 PDF 텍스트를 만들고, PDF 문서에 테이블을 생성하고, 워터마크를 페이지에 추가하는 클래스가 포함되어 있다. iText로 사용할 수 있는 더 많은 기능들이 있다. 하지만 그 모든 것을 이 글에서 다 설명하기는 불가능하다. PDF 생성에 필요한 기본적인 것만을 설명하겠다.

샘플 애플리케이션 개발에 Eclipse를 사용할 것이다. 오픈 소스 IDE인 Eclipse는 무료로 사용할 수 있고 매우 강력하다. 지금 Eclipse를 다운로드 하라. (참고자료)

iText API

com.lowagie.text.Document는 PDF 문서 생성을 위한 주 클래스이다. 인스턴스로 만들어질 첫 번째 클래스이다. 문서가 생성되면 라이터는 여기에 작성해야 한다. com.lowagie.text.pdf.PdfWriter는 PDF 라이터이다. 다음은 일반적으로 사용되는 클래스들이다.

  • com.lowagie.text.Paragraph -- 들여쓰기 단락을 나타내는 클래스이다.
  • com.lowagie.text.Chapter -- PDF 문서의 챕터이다. 타이틀로 Paragraph를 사용하고, 챕터 번호로 int를 사용한다.
  • com.lowagie.text.Font -- 폰트, 크기, 스타일, 컬러 같은 모든 폰트 스팩들이 포함되어 있다. 다양한 폰트들은 이 클래스에 정적 상수로서 선언된다.
  • com.lowagie.text.List -- 많은 ListItems를 포함하고 있는 리스트이다.
  • com.lowagie.text.Table -- 매트릭스에서 정렬된 셀들을 포함하고 있는 테이블이다.

Eclipse에서 iText 다운로드 및 설정하기

순수 자바 라이브러리인 아아텍스트는 JAR 파일의 형태로 되어 있다. (참고자료.) 라이브러리를 다운로드 하면(C:\temp) Eclipse 환경에서 iText 라이브러리를 설정한다.

  1. Eclipse에서 iText라는 이름의 새로운 자바 프로젝트를 만든다.
  2. Package Explorer 뷰에서 iText 프로젝트를 오른쪽 클릭하고 Properties를 선택한다.
  3. Java Build Path를 클릭한다. Libraries 탭에서, Add External JARs를 클릭한다.
  4. C:\temp 디렉토리를 검색하여 itext-1.3.jar를 선택한다.
  5. OK를 클릭한다.

iText가 설정되면 Eclipse는 동적인 PDF 문서를 생성하는 자바 애플리케이션을 구현할 준비를 갖춘 것이다.

샘플 애플리케이션

직접 샘플을 만드는 것 만큼 확실한 설명 방법은 없다. 필요한 툴(Eclipse IDE)과 라이브러리(iText 라이브러리)가 준비되었으니 샘플 프로그램을 디자인 및 개발해 보자.

평이한 텍스트, 특별 폰트로 색상을 입힌 텍스트, 테이블, 리스트, 챕터, 섹션 같은 기본적인 엘리먼트를 포함하고 있는 PDF 문서를 만들어 보자. 이 애플리케이션의 목적은 여러분이 iText 라이브러리를 사용하는 방법을 보다 잘 이해할 수 있도록 돕는 것이다. PDF 문서 생성과 관련되어 많은 일을 수행하는 많은 클래스들이 있다. 이 모든 클래스들을 다 다루기는 불가능하다. iText의 javadoc은 이러한 클래스들의 사용법을 잘 이해할 수 있는 좋은 자료이다. 코딩부터 시작해 보자.

첫 번째 단계는 문서를 만드는 것이다. 이 문서는 PDF 문서의 모든 엘리먼트용 컨테이너이다.


Listing 1. 문서 객체의 인스턴스화
				
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

첫 번째 인자는 페이지 크기이다. 다음 인자들은 각각 왼쪽, 오른쪽, 상단, 하단 여백들이다. 이러한 유형의 문서는 아직 정의되지 않았다. 여러분이 만드는 라이터의 유형에 의존한다. 이 샘플에서 우리는 com.lowagie.text.pdf.PdfWriter를 선택했다. 기타 라이터로는 HtmlWriter, RtfWriter, XmlWriter 등이 있다. 이름만으로도 충분히 그 용도를 알 수 있다.


Listing 2. PdfWriter 객체의 생성
				
PdfWriter writer = PdfWriter.getInstance(document, \
new FileOutputStream("C:\\ITextTest.pdf"));
document.open();

첫 번째 인자는 문서 객체에 대한 참조이고, 두 번째 인자는 아웃풋이 작성될 파일의 고유 이름이다. 작성을 위해 문서를 연다.

이제, 문서의 첫 번째 페이지에 몇 가지 텍스트를 추가할 것이다. com.lowagie.text.Paragraph을 사용하여 어떤 텍스트라도 추가된다. 텍스트로 기본 단락을 만들고 폰트, 컬러, 크기 등 기본적인 설정을 할 수 있다. 각자의 고유 폰트를 사용해도 된다. 두 가지 옵션 모두를 살펴보자.


Listing 3. 단락 객체의 생성
				
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("Some more text on the \
first page with different color and font type.", 
FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));

아래 그림은 위 코드의 아웃풋이다. 위 코드 말미에 document.close();을 추가하여 문서를 마감한다.


그림 1. 아웃풋
Sample output of above code 

평이한 텍스트를 PDF 문서에 추가하는 방법을 배웠다. 복잡한 요소들도 문서에 추가해야 한다. 새로운 챕터를 만든다. 이 챕터는 특별 섹션으로서 새로운 페이지로 시작하고 기본적으로 디스플레이 된 숫자가 있다.


Listing 4. 챕터 객체의 생성 
				
Paragraph title1 = new Paragraph("Chapter 1", 
           FontFactory.getFont(FontFactory.HELVETICA, \
           18, Font.BOLDITALIC, new Color(0, 0, 255)));
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);

위 코드에서 chapter1 이라는 새로운 챕터 객체를 만들었다. 제목은 "This is Chapter 1."이다. 숫자 한계를 0으로 설정하면 페이지에 챕터 번호가 디스플레이 되지 않는다.

섹션은 챕터의 하위 요소이다. 다음 코드에서, "This is Section 1 in Chapter 1." 이라는 제목의 섹션을 만들었다. 이 섹션에 텍스트를 추가하기 위해 또 다른 단락 객체인 someSectionText를 만들고 이를 섹션 객체에 추가한다.


Listing 5. 섹션 객체의 생성 
				
Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1", 
           FontFactory.getFont(FontFactory.HELVETICA, 16, \
           Font.BOLD, new Color(255, 0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This \
text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);

테이블을 추가하기 전에 문서가 어떤 모습인지를 보자. 다음 두 줄을 추가하여 문서를 종료하고 프로그램을 컴파일 및 실행하여 PDF 문서를 만든다. document.add(chapter1);document.close();.


그림 2. 아웃풋
Sample output of chapter 

이제 테이블 객체를 만들어 보자. 테이블에는 열과 칼럼의 매트릭스가 포함된다. 한 열의 셀은 한 개 이상의 칼럼으로 확장될 수 있다. 마찬가지로, 한 칼럼에 있는 셀은 한 개 이상의 열로 확장될 수 있다. 따라서, 3 x 2 테이블은 정확히 6 개의 셀만 가질 필요가 없다.


Listing 6. 테이블 객체의 생성
				
Table t = new Table(3,2);
t.setBorderColor(new Color(220, 255, 100));
t.setPadding(5);
t.setSpacing(5);
t.setBorderWidth(1);
Cell c1 = new Cell("header1");
c1.setHeader(true);
t.addCell(c1);
c1 = new Cell("Header2");
t.addCell(c1);
c1 = new Cell("Header3");
t.addCell(c1);
t.endHeaders();
t.addCell("1.1");
t.addCell("1.2");
t.addCell("1.3");
section1.add(t);

위 코드에서, t라는 테이블 객체를 만들었다. 세 개의 칼럼과 두 개의 열을 갖고 있다. 테이블의 보더 색상을 설정했다. 패딩(padding)은 셀의 텍스트와 셀의 경계간 공간을 만드는데 사용된다. 스페이싱(spacing)은 인접하는 셀의 경계들간 공간이다. 그런 다음, 세 개의 셀 객체를 만든다. 각각 다른 텍스트를 갖고 있다. 이들을 계속해서 테이블에 추가한다. 첫 번째 칼럼에서 시작하여 같은 열의 다음 칼럼으로 이동한다. 열이 완성되면 다음 셀이 다음 열의 첫 번째 칼럼에 추가된다. 셀은 t.addCell("1.1"); 같은 셀의 텍스트를 제공하여 테이블에 추가될 수 있다. 마지막으로 테이블 객체가 섹션 객체에 추가된다.

마지막으로 PDF 문서에 리스트를 추가해 보자. 리스트에는 많은 ListItem들이 추가된다. 리스트에는 번호가 붙을 수도 있고 붙지 않을 수도 있다. 첫 번째 인자를 TRUE로 전달하면 번호가 붙은 리스트를 만들어야 한다.


Listing 7. 리스트 객체의 생성
				
List l = new List(true, false, 10);
l.add(new ListItem("First item of list"));
l.add(new ListItem("Second item of list"));
section1.add(l);

지금까지 chapter1 객체에 모든 것을 추가했다. chapter1에 추가될 더 이상의 객체가 없기 때문에, chapter1을 주 document에 추가해야 한다. 샘플 애플리케이션을 통해 한 개의 문서를 완성했다.


Listing 8. 주 document에 챕터 추가하기 
				
document.add(chapter1);
document.close();

샘플 애플리케이션 실행하기

  1. 샘플 애플리케이션, j-itextsample.jar(Download)을 다운로드 한다.
  2. 디렉토리에 j-itextsample.jar의 압축을 푼다. C:\temp에 추출하면, 소스와 클래스 파일은 C:\temp\com\itext\test에 배치된다.
  3. 명령어 프롬프트를 열고 디렉토리를 C:\temp로 변경한다.
  4. 명령어 프롬프트에 시스템의 classpath를 설정한다. 시스템의 classpath에 C:\temp\itext-1.3.jar를 포함시킨다. Windows®에서는, set classpath=C:\temp\itext-1.3.jar;%classpath%명령어를 실행한다.
  5. java com.itext.test.ITextTest 명령어로 애플리케이션을 실행한다.

이 프로그램은 C:\에 ITextTest.pdf 문서를 생성할 것이다. 아래 그림은 이 PDF 문서의 두 번째 페이지 모습이다.


그림 3. PDF 문서 모습
Screenshot of PDF document 

결론

지금까지 PDF 생성을 위한 기본 요소들을 살펴 보았다. iText의 장점은 같은 엘리먼트의 신택스가 다른 유형의 라이터에도 사용될 수 있다는 점이다. 또한, 이 라이터의 결과는 콘솔( XML과 HTML 라이터), 서블릿의 아웃풋 스트림 (PDF 문서의 웹 요청에 대한 응답), 또는 다른 유형의 OutputStream 으로 리다이렉션 된다. 또한 iText는 응답은 갖지만 PDF, RTF, HTML, XML 등 다양한 응답 유형을 보이는 상황에서 편리하게 사용할 수 있다. iText에서는 워터마크를 만들 수 있고 문서를 암호화 할 수 있으며 아웃풋도 정확하다.

:
Posted by 라면스프
출처 : http://www.ibm.com/developerworks/kr/library/j-5things11/index.html


JVM의 명령행 플래그에 대해 모르고 있던 5가지 사항


 

JVM 성능 및 Java 런타임 정밀 조정하기
 

JVM은 Java 애플리케이션의 기능과 성능을 뒷받침하는 일꾼이지만 대부분의 Java 개발자는 이를 당연한 것으로 여기고 중요하게 생각하지 않는다. 그리고 오브젝트 할당 및 가비지 콜렉션, 스레드 실행, 파일 열기 및 닫기, Java 바이트코드 해석 및/또는 JIT 컴파일 등의 작업이 JVM에서 처리되는 방법을 제대로 이해하고 있는 개발자는 거의 없다.



애플리케이션 성능에 영향을 주는 JVM 기능에 익숙하지 않을 때뿐만 아니라 JVM에서 오류가 발생한 경우에도 문제점을 해결하기가 매우 어려울 수 있다.

5가지 사항 시리즈의 이 기사에서는 Java 가상 머신의 성능을 진단 및 조정하는 데 사용할 수 있는 여러 가지 명령행 Java 플래그를 소개한다.

1. DisableExplicitGC

필자는 애플리케이션 성능 문제점에 대한 상담 의뢰를 받고 코드 전체에 대해 빠른 grep을 수행하여 원래 Java 성능 안티 패턴인 Listing 1과 같은 내용을 발견한 경험이 얼마나 많은지 모른다.


Listing 1. System.gc();
// We just released a bunch of objects, so tell the stupid
// garbage collector to collect them already!
System.gc();

명시적 가비지 콜렉션은 정말로 나쁜 아이디어이다. 이는 마치 공중전화 부스 속에 자기 자신을 광견병에 걸린 개와 함께 가둬놓는 것과 비슷하다. 구현에 따라 호출의 정확한 의미가 달라지기는 하지만 JVM이 제너레이셔널(generational) 가비지 콜렉터(대부분의 가비지 콜렉터가 제너레이셔널 가비지 콜렉터임)를 실행하고 있을 경우 System.gc();를 실행하면 전체 삭제가 필요하지 않더라도 VM이 힙을 "전체 삭제"하게 된다. 일반적으로 전체 삭제에는 일반적인 GC 조작보다 몇 배나 더 높은 비용이 소요된다. 이는 분명 어리석은 방법이다.

하지만 이 말을 그대로 받아들이면 안 된다. 왜냐하면 Sun의 엔지니어가 이 특별한 인적 오류 문제점을 해결하기 위한 JVM 플래그를 제공했기 때문이다. -XX:+DisableExplicitGC 플래그는 자동으로 System.gc() 호출을 무작동으로 전환한다. 따라서 코드를 실행한 후System.gc()가 JVM의 전체 실행에 도움이 되는지 아니면 해가 되는지 여부를 직접 확인할 수 있다.



2. HeapDumpOnOutOfMemoryError

근래에 OutOfMemoryError가 발생하면서 JVM이 종료될 뿐만 아니라 디버거를 사용하여 오류를 찾고 문제점을 확인할 수도 없는 상황을 경험한 적이 있는가? 원인을 알 수 있는 이와 같은 문제점이 발생하면 개발자가 화가 나서 정신을 차리기 어려울 것이다.

사용자 책임

Sun/Oracle의 VM 이외의 다른 VM에서는 일부 명령행 플래그가 지원되지 않을 수도 있다. 플래그의 지원 여부를 가장 효과적으로 확인하는 방법은 무엇보다도 직접 사용해 보고 작동하는지 확인하는 것이다. 하지만 이러한 플래그가 기술적으로 지원되지 않더라도 플래그 사용에 대한 책임은 전적으로 사용자 자신에게 있다. 필자뿐만 아니라 Sun/Oracle 또는 IBM®마저도 이러한 플래그로 인해 코드, 데이터 또는 서버가 크게 손상되더라도 그 어떠한 책임을 지지 않는다. 따라서 미리 주의를 주지만 가상(비프로덕션) 환경에서 먼저 사용해 보기를 권장한다.

JVM이 종료되려는 순간에 힙의 스냅샷을 작성하고 싶은 경우가 있다. 바로 이 기능을 -XX:+HeapDumpOnOutOfMemoryError 명령이 수행한다.

이 명령을 실행하면 JVM이 "힙 덤프 스냅샷"을 작성한 후 처리를 위해 파일에 저장한다. 일반적으로 이 작업에는 jhat 유틸리티(필자의 이전 기사 참조)가 사용된다. 해당 -XX:HeapDumpPath 플래그를 사용하여 파일을 저장할 실제 경로를 지정할 수 있다. (파일이 어느 위치에 저장되던지 상관 없이 파일 시스템 및/또는 Java 프로세스에 해당 위치에 작성할 수 있는 권한이 있는지 확인한다.)




3. bootclasspath

설치된 JRE에 포함되어 있는 경로 또는 JRE를 조금 확장한 경로와는 약간 다른 클래스 경로에 클래스를 주기적으로 저장해 두는 것이 좋다. (새 Java Crypto API 제공자가 예가 될 수 있을 것이다.) JRE를 확장하려고 하면 사용자 정의 구현을 부트스트랩 ClassLoader에서 사용할 수 있어야 하며, 이 클래스 로더는 java.lang.Object 및 rt.jar의 모든 항목을 로드한다.

크랙을 사용하여 rt.jar을 열고 사용자 정의 구현 또는 새 패키지를 넣을 수도 있겠지만 이는 JDK를 다운로드할 때 동의했던 라이센스를 기술적으로 위반하는 것이다.

대신 JVM 자체의 -Xbootclasspath 옵션을 -Xbootclasspath/p 및 -Xbootclasspath/a와 함께 사용한다.

-Xbootclasspath를 사용하면 전체 부트 클래스 경로를 설정할 수 있으며, 이 클래스 경로는 일반적으로 rt.jar에 대한 참조를 포함해야 하며 rt.jar에 포함되지 않은 JDK의 다른 JAR 파일 세트도 포함해야 한다. -Xbootclasspath/p는 값을 기존 부트 클래스 경로 앞에 추가하고, -Xbootclasspath/a는 값을 뒤에 추가한다.

예를 들어, 설치된 java.lang.Integer를 수정한 후 수정 사항을 서브디렉토리 mods에 저장한 경우 -Xbootclasspath/a mods 매개변수는 새 Integer를 기본값 앞에 놓는다.



4. verbose

-verbose는 거의 모든 유형의 Java 애플리케이션에 사용할 수 있는 유용한 1차 진단 유틸리티이다. 이 플래그에는 gcclass 및 jni라는 세 개의 서브플래그가 있다.

gc는 작동 중인 JVM 가비지 콜렉터로 인해 성능이 저하되었는지 확인할 때 가장 먼저 사용되는 도구이다. 아쉽게도 gc의 출력에 대한 해석은 한 권의 책으로 다루어질 정도로 까다롭다. 게다가 명령행에 인쇄되는 출력이 Java 릴리스 또는 JVM별로 다를 수 있기 때문에 올바르게 해석하기가 더욱 어렵다.

일반적으로 말해서, 가비지 콜렉터가 제너레이셔널 콜렉터(대부분의 "엔터프라이즈급" VM)이면 전체 삭제 GC 패스를 나타내는 일종의 시각적 플래그가 표시된다. Sun JVM의 경우에는 플래그가 GC 출력 행의 맨 앞에 "[Full GC ...]"로 표시된다.

class는 ClassLoader 및/또는 일치하지 않는 클래스 충돌을 진단하는 데 도움이 되는 도구이다. 이 플래그는 클래스의 로드 시간뿐만 아니라 JAR 파일에 대한 경로를 포함한 클래스의 원본 위치까지도 보고한다(JAR에서 로드된 것으로 가정).

jni는 JNI 및 네이티브 라이브러리 작업 외에는 거의 사용되지 않는다. 이 플래그를 사용하면 네이티브 라이브러리가 로드되었거나 메소드가 바인드되었다는 등의 다양한 JNI 이벤트가 보고된다. 다시 한번 말하지만 JVM의 릴리스별로 출력이 달라질 수 있다.



5. 명령행 -X

지금까지 JVM에서 제공하는 명령행 옵션 중에서 필자가 좋아하는 몇 가지 옵션을 살펴보았다. 하지만 직접 찾아볼 수 있는 더 많은 옵션이 있다. 명령행 인수 -X는 JVM에서 제공하는 모든 비표준(하지만 대부분 안전한) 인수를 나열한다. 예를 들어, 다음과 같다.

  • -Xint는 JVM을 해석된 모드로 실행한다. (이 인수는 JIT 컴파일러가 코드에 실제로 영향을 주는지 테스트하거나 JIT 컴파일러에 버그가 있는지 확인할 때 유용하다.)
  • -Xloggc:는 -verbose:gc와 동일한 기능을 제공하지만 명령행 창에 표시하는 대신 파일에 로깅한다.

JVM 명령행 옵션은 때때로 변경되므로 주기적으로 확인하는 것이 좋다. 모니터를 보고 있던 늦은 밤 중이나, 가족과 함께 저녁 만찬을 하기 위해 오후 5시에 퇴근하는 중이나 아니면 Mass Effect 2에서 적을 무찌르는 동안에 변경될 수도 있다.



결론

명령행 플래그는 프로덕션 환경에서 지속적으로 사용하기 위한 것이 아니다. JVM 가비지 콜렉터를 조정하기 위해 사용하는 플래그를 제외하고, 비표준 명령행 플래그는 실제로 프로덕션용이 아니다. 하지만 제대로 알기 힘든 가상 머신의 내부 작업을 살펴볼 수 있는 도구라는 점에서 이러한 태그는 매우 유용하다.

5가지 사항 시리즈의 다음 주제는 일상적인 Java 도구이다. 

:
Posted by 라면스프
2012. 3. 9. 15:26

[TOMCAT] Tomcat Performance Tuning Enjoy/etc2012. 3. 9. 15:26

출처 : http://www.solutionhacker.com/tomcat-performance-tuning/


Most companies I have worked for use Tomcat as Servlet Container. It is de facto standard just like how Apache been used as Web Server. However, most of us just drag our war file to the webapp folder and use Tomcat with all the settings as default out of the box. It works fine in development environment but may not in production. This article will give you advice in several areas:

  1. Production Tomcat Architecture
  2. Tuning tomcat for performance
  3. Resolving problems which affect availability

 Production Tomcat Architecture

In production Tomcat relies on a number of resources which can impact its overall performance. Understanding the overall system architecture is key to tuning performance and troubleshooting problems.

  1. Hardware: CPU(s), memory, network IO and file IO
  2. OS: SMP (symmetric multiprocessing) and thread support
  3. JVM: version, tuning memory usage, and tuning GC
  4. Tomcat: version (example, Tomcat 6 supports NIO)
  5. Application: Application design can have the largest impact on overall performance
  6. Database: concurrent db connection is allowed (pooling and object caching)
  7. Web Server: Apache can sit in front of Tomcat and serves the static content. It also can do load balancing across multiple Tomcat instances.
  8. Network: Network delays.
  9. Remote Client: How fast is the communication protocol? Content can be compressed. 

Performance Tuning

How to measure and test performance

  • Request latency is key b/c it reflects the responsiveness of your site for visitors.
  • Test environment should match production as closely as possible.
  • The data volume is important to simulate in database side.
  • Test HTTP requests with different request parameters (test corner cases)
  • Use load test to simulate the traffics (ex. JMeter)
  • Final tests should be over longer periods like days because JVM performance changes over time and can actually improve if using HotSpot. Memory leaks, db temporary unavailable, etc can only be found when running longer tests.

JVM version, memory usage and GC

  • Sun Java 1.3 and later releases inlcude HotSpot profiling optimizer customized for long running server application.
  • Tomcat will freeze processing of all requests while the JVM is performingGC. On a poorly tuned JVM this can last 10′s of seconds. Most GC’s should take < 1 second and never exceed 10 seconds
  • Tune the -Xms (min) and -Xmx (max) java stack memory (set them to the same value can improve GC performance)
  • Make sure the java process always keeps the memory it uses resident in physical memory and not swapped out to virtual memory.
  • Use -Xincgc to enable incremental garbage collection
  • Try reducing -Xss thread stack memory usage

Tomcat version and configuration

  • Tomcat 6 supports NIO.
  • Set “reloadable” false – remove unnecessary detection overhead
  • Set “liveDeploy” to false – liveDeploy controls whether your webapps directory is periodically checked for new war files. This is done using background thread.
  • Set “debug” to 0
  • Set “swallowOutput” to true – This makes sure all output to stdout or stderr for a web application gets directed to the web application log rather than the console or catalina.out. This make it easier to troubleshoot problems.
  • Connector configuration – minProcessor, maxProcessor, acceptCount, enableLookups. Don’t set the acceptCount too high b/c this sets the number of pending requests awaiting processing. It is better deny few requests than overload Tomcat and cause problems for all requests. Set “enableLookups” to false b/c DNS lookups can add significant delays.

Database connection pool

  • We use connection pool provided by Spring instead
  • Using middleware to persist and cache objects from your database can significantly improve performance b/c of fewer db calls, less thrashing of the JVM for creation and subsequent GC of object craeted for resultset.

Application design and profiling

  • If the data used to generate a dynamic page rarely changes, modify it to a static page which you regenerate periodically.
  • Cache dynamic page
  • Use tool like JProble to profle your web applications during development phase
  • Look for possible thread synchronization bottlenecks
  • Date and Time thread synchronization bottleneck 

Troubleshooting

Collecting and analyzing log data

Common problems

  • Broken pipe – For HTTP Connector indicates that the remote client aborted the request. For web server JK Connector indicates that the web server process or thread was terminated. These are normal and rarely due to a problem with Tomcat. However, if you have long request, the connectionTimeout may close the connection before you send your response back.
  • Tomcat freezes or pauses with no request being processed – usually due to a long pause of JVM GC. A long pause can cause a cascading effect and high load once Tomcat starts handling requests again. Don’t set the “acceptCount” too high and use java -verbose:gc startup argument to collect GC data.
  • Out of Memory Exception – look into application code to fix the leak (profile tool can help). Increase available memory on the system via -Xmx. Restart tomcat!
  • Database connection failure – connection used up when traffic is spike.
  • Random connection close exception - when you close your connection twice. First close(), the connection returns to the pool. It may be picked up by another thread. Now, second close() may close a connection that is being used by other thread. Don’t close connection twice, use JDBC Template from Spring to avoid this problem. 

Reference

  1. JavaWorld GC Article
  2. Sun HotSpot Performance Document
  3. Tomcat Performance Slides

  

:
Posted by 라면스프
출처 : http://www.java-tips.org/java-tutorials/tutorials/introduction-to-java-servlets-with-eclipse.html


Introduction

Java Servlet is the one of the most important Java technologies. It is the simplest model to build a complete Java J2EE Web Application. Furthermore, even for complex J2EE Web Application that uses Struts, Spring, EJB and etc, they are still using Servlet for certain purposes such as Servlet Filter, Listener and etc. Thus, it is just a good idea for you to have well-built understanding of Java Servlet. Prior reading this tutorial, it would be excellent if you have mastered the basic Java programming languages.

At the completion of the tutorial, you are expected to comprehend the concept of the Java Servlet, be familiar with the ways to create Java Servlet using Eclipse 3.1.2, differences between POST and GET and should be ready to go to the next level.

In this tutorial, we are going to create one dynamic web application that asks the user for first name and surname. Then the system should response by greeting the users.

The tutorial consists of four main steps.

  1. Introduction to Eclipse 3.1.2
  2. Creating New Web Application Project in Eclipse 3.1.2 with Web Tools Platform (WTP) Plug-in.
  3. Creating Server Definition in Eclipse 3.1.2
  4. Implementation of Tutorial’s Example
  5. How to Start Tomcat Manually
  6. How to Shutdown Tomcat Manually
  7. Conclusion



Introduction to Eclipse 3.1.2

Nowadays, many J2EE developers are using Eclipse as their IDE for Java programming language. One of the reasons is that Eclipse is free and is easily extendable. Yes, that is correct, there are plentiful plugins available in Internet for Eclipse. Additionally, the famous IBM WebSphere Application Developer for developing J2EE application in WebSphere is also implemented above the Eclipse framework.

Besides Java programming, Eclipse can also be used to edit any file such as C++, C or PHP and etc. You need to remember that Eclipse does not have any server embedded in it. Eclipse is just an editor. Well, let’s start to explore on how Eclipse can assist you in creating a Java Servlet.

Creating New Web Application Project in Eclipse 3.1.2 with Web Tools Platform (WTP) Plug-in

Okay, for our tutorial, we are going to exercise Web Tools Platform (WTP) plugin. I would suggest you to download Web Tools Platform (WTP) together with Eclipse so you should not be bothered on how to install the plugin into Eclipse and etc. Ideally, if you download Eclipse without any plugin, it does not have any support for J2EE Development. That is the core reason why various vendors are implementing J2EE plugins for Eclipse. Web Tools Platform is not the only J2EE plugin available for Eclipse. There are numerous J2EE plugins available in Internet such as Lomboz from ObjectLearn, MyEclipse and etc. If you are interested to know deeper on Eclipse plugin, you can visithttp://www.eclipseplugincentral.com/ for the complete list of available plugins for Eclipse.

To download Web Tools Platform (WTP), you can go to http://www.eclipse.org/webtools/ and you can download it together with Eclipse by choosing the download link on the left panel of that particular site. Web Tools Platform (WTP) plugin with Eclipse is approximately 182 MB. It will be in zip file and you will not have installation for it. You can extract it to C:\ and you can directly use Eclipse by double clicking the Eclipse.exe file in the extracted folder.

Unlike NetBeans, Eclipse does not have any server embedded in it thus, in order to create a Java Servlet in Eclipse; you need to install the server (for our tutorial, you need Apache Tomcat) as well as the Java Development Kit (JDK) from Sun.

Before going further to our tutorial, it would be good if you understand the concept of Java Servlet as explained in the next paragraphs.

Creating a Java Servlet means that you are required to deal with JSP (JavaServer Pages). JSP is actually a HTML but unlike HTML, JSP may have Java codes (usually we call it as Scriptlet) embedded in it. In short words, we may represent JSP as dynamic HTML. In Java J2EE Web Application, JSP plays as a front-end while Java Servlet is the controller that contains the business logics, complex algorithms and etc.

For example, consider “Online University Student Registration System” developed in Java J2EE Web Application, the registration page where you fill in your details such as your name, your address, your username and etc are actually a JSP page. Later on, when you have completed filling out all the details and you press the submit button, all the information will be sent to Java Servlet for further processes. Java Servlet receives this information, does the necessary processes such as validations, generating user id and etc and then keeps the information to database. After successfully saving the data to database, Java Servlet redirects the user to the success page where the user can log in to the system. Likewise, if there is an unexpected error occurred happening in the middle of student registration system’s process, the user will be redirected to the error page.

Assuming that you have installed Eclipse with Web Tools Platform (WTP) Plugin, Java Development Kit 1.5 and Tomcat Server 5.5, let’s start to create our first Java Servlet. Start Eclipse and you should see similar to below illustration in your screen. Yes, this is the main page of Eclipse.



Image 

To create our Java Servlet, we are required to create a Project called Dynamic Web Project. Go to your menu, choose New and Project. A wizard will be prompted to you.



Image 

Go to the Web and choose Dynamic Web Project and press Next. If you do not have Dynamic Web Project available, it means that Web Tools Platform (WTP) plugin is not correctly installed to Eclipse. Please re-download it or look at the documentation of Web Tools Platform (WTP) plugin for more details.



Image 

A wizard will be displayed to you. The wizard is mainly used to configure our Dynamic Web Project. You are allowed to name your Dynamic Web Project with any name that you wish but please consider to choose the name that is self-explanatory.

For our tutorial’s sample, I am going to name my Dynamic Web Project as MyFirstServlet. There is an interesting point worth to be looked at in this wizard. You need to provide the Target Runtime. What does it mean? Well, it basically requests you to identify the server that you would like to use for this Dynamic Web Project; in this case, Apache Tomcat. You may try to click on the combo box to observe whether you have any existing server(s) or not. If not, you are required to create one server for your project. If this is the first time you run Eclipse, you should not have any server yet. So, click on the New button on the right side of the Target Runtime combo box. Remember, after defining one server, you can re-use it in other projects so you do not need to define new server in every project unless if you wish to use other servers than Tomcat such as Bea WebLogic and etc.



Image 
:
Posted by 라면스프