블로그 이미지
좋은느낌/원철
이것저것 필요한 것을 모아보렵니다.. 방문해 주셔서 감사합니다..

calendar

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

Notice

    2009. 7. 2. 09:47 개발/JSP/Servlet

    Tomcat + SSL

    Authenticating Clients (with SSL)

    디지털 커머스의 증가와 중요한 데이터간의 이동이 필요함에 따라서 보안은 모든 어플리케이션에서 중요한 자리를 차자하고 있습니다. 일반적으로 client 와 서버간에 사용자를 확인하기 위한 방법으로 username 과 password 를 체크합니다. 이를 사용하는 보안 처리 기법으로 Secure Sockets Layer (SSL) 과 Java Authentication and Authorization Service (JAAS)를 사용할 수가 있습니다. 먼저 SSL로 보안인증을 거치는 방법을 보고 java 에서 지원하는 다른 사용자 인증서비스인 JAAS을 jsp와 서블릿에서 사용하는 법을 보겠습니다.

    1. 톰켓에서 사용자 인증 처리하기

    톰켓으로 사용자 인증처리를 하기전에 먼저 username, password, role 을 등록해야 합니다. 등록하는 방법은 아주 쉽습니다. 톰켓이 설치된 폴더에서 /conf 에 보면 tomcat-user.xml 파일이 있습니다. 없으면 에디터 창에서 새로 만들어도 됩니다. 

    <?xml version='1.0' encoding='utf-8'?><?xml version='1.0' encoding='utf-8'?> 
    <tomcat-users> 
        <role rolename="dbadmin"/> 
        <role rolename="manager"/> 
        <user username="hans" password="hansworld" roles="dbadmin,manager"/> 
        <user username="jojo" password="33dsk3" roles="manager"/> 
    </tomcat-users> 

    위 소스에서 hans는 dbadmin과 manager의 권한을 갖고 jojo는 manager의 권한을 갖습니다. 

    다음으로 톰켓서버에서 SSL을 셋팅해야 합니다. 이는 username이나 password 가 http상에서 이동할 때 암호화 되어 이동하기 때문에 중간에 악의적인 의도로 가로채거나 훔쳐내는 것을 방지해 줍니다. SSL을 셋팅하기 위해선 2가지 절차를 거쳐야 합니다.

    1. java sdk에서 지원해주는 keytool로 keystore 파일을 만듭니다. 이 파일은 보안 접속을 하는 서버가 디지털 인증을 암호화 해서 사용하는데 쓰여집니다. 
    2. 톰켓의 conf/server.xml 파일에 SSL Connector에 있는 주석을 제거합니다.

    keytool은 java가 설치된 in 에서 찾을 수 있습니다. 

    %JAVA_HOME%inkeytool -genkey -alias tomcat -keyalg RSA 


    위의 명령을 실해하면 keystore 파일이 생성되는데 몇가지 질문을 합니다. 처음으로 패스워드를 물어보는데 톰켓에서 기본적으로 "changeit" 란 패스워드로 셋팅되어 있습니다. 나머지는 원하지 않으면 그냥 엔터키만 치면 됩니다. 

    Enter keystore password: changeit 
    What is your first and last name? 
    [Unknown]: Bruce Perry 
    What is the name of your organizational unit? 
    [Unknown]: 
    What is the name of your organization? 
    [Unknown]: 
    What is the name of your City or Locality? 
    [Unknown]: 
    What is the name of your State or Province? 
    [Unknown]: 
    What is the two-letter country code for this unit? 
    [Unknown]: 
    Is CN=Bruce Perry, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct? [no]: yes 
    Enter key password for <tomcat>
    (RETURN if same as keystore password):

    다음에 conf/server.xml 에 있는 SSL Connector 요소에 있는 주석을 제거합니다.

    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <connector disableuploadtimeout="true" useurivalidationhack="false" secure="true" scheme="https" debug="0" acceptcount="100" enablelookups="true" maxprocessors="75" minprocessors="5" port="8443" classname="org.apache.coyote.tomcat4.CoyoteConnector">
    <factory classname="org.apache.coyote.tomcat4.CoyoteServerSocketFactory" protocol="TLS" clientauth="false" />
    </connector>

    SSL은 일반 http 가 아닌 https 를 사용합니다. 또한 포트도 웹에서 80, 톰켓에서 8080 처럼 8443의 번호를 사용합니다.

    https://localhost:8443/myhome/default.jsp



    2. BASIC authentication BASIC Authentication


    Basic 인증은 웹자원과 함께 사용되어온 보안 방법이고 거의 모든 브라우져가 이를 지원합니다. 일반적으로 사용자 이름과 비밀번호를 전송할 때 네트워크 상에서 Base64 인코딩 방식을 사용하는데 이는 디코딩하기 아주 쉽기때문에 보안적이라고 할 수 없습니다. 따라서 Basic Authentication 과 SSL 을 사용한 보안 방식을 사용합니다.

    1. 먼저 처음에 설명했지만 username, password, role을 conf/tomcat-users.xml 에서 설정합니다.
    2. security-constraint element 로 인증에 필요한 자원을 web.xml 파일에 기술합니다.
    3. "BASIC"이라고 auth-method요소 사이에 적습니다. 이 auth-method 요소는 login-config요소에 들어갑니다.

    <!-- Beginning of web.xml deployment descriptor -->
    <security-CONSTRAINT>
    <web-RESOURCE-COLLECTION>
    <web-RESOURCE-NAME>JSP database component</web-RESOURCE-NAME> 
    <url-PATTERN>/myhome.jsp</url-PATTERN> 
    <http-METHOD>GET</http-METHOD> 
    <http-METHOD>POST</http-METHOD> 
    </web-RESOURCE-COLLECTION>
    <auth-CONSTRAINT>
    <role-NAME>dbadmin</role-NAME> 
    </auth-CONSTRAINT>
    <user-DATA-CONSTRAINT>
    <transport-GUARANTEE>CONFIDENTIAL</transport-GUARANTEE> 
    </user-DATA-CONSTRAINT>
    </security-CONSTRAINT>
    <login-CONFIG>
    <auth-METHOD>BASIC</auth-METHOD> 
    </login-CONFIG>
    <security-ROLE>
    <role-NAME>dbadmin</role-NAME> 
    </security-ROLE>
    <!-- Rest of web.xml deployment descriptor -->

    web.xml 을 이렇게 편집한 후에 https://localhost:8443/myhome.jsp 로 들어가보면 아이디와 비밀번호를 입력하라는 창이 뜹니다. 여기서 만일 role 이 dbadmin 이 아니라면 아이디와 비밀번호가 맞아도 인증에 실패하게 됩니다. 반드시 해당 사용자가 인증에 필요한 role을 가지고 있어야 합니다.



    3. Form-Based Authentication 의 사용 

    서블릿은 일반 BASIC authentication 말고도 사용자 기반 인증인 Form-Based Authentication 제공합니다. 이는 톰켓에서 보여주는 BASIC authentication 의 단순화를 덜어주며 일반적으로 사용하는 form 방식을 사용하기 때문에 이용하기도 편합니다. 이역시 SSL 과 HTTPS를 사용하여 네트워크상에서 이동하는 데이터들을 보호합니다.

    먼저 web.xml 셋팅을 보겠습니다. 파일의 맨 처음부분에 보안 관련 element를 기술하게 됩니다. security-constraint 부분은 BASIC authentication 과 같습니다. login-config 셋팅부분이 약간 다르긴 하지만 그렇게 크게 다르지는 않습니다.

    <login-CONFIG>
    <auth-METHOD>FORM</auth-METHOD>
    <form-LOGIN-CONFIG>
    <form-LOGIN-PAGE>/login.html</form-LOGIN-PAGE>
    <form-ERROR-PAGE>/loginError.jsp</form-ERROR-PAGE>
    </form-LOGIN-CONFIG>
    </login-CONFIG>

    실제 jsp에서 
    <form>테그를 사용하여 사용자 정보를 전송하는데 이때 주의할 점은 form 태그의 action 요소의 값을 'j_security_ckeck' 로 하고 사용자 이름과 비밀번호의 이름을 'j_username' 과 'j_password'로 해야합니다. 로그아웃 시에는 HttpSession 객체의 invalidate() 메소드를 호출하면 됩니다.</form>
    posted by 좋은느낌/원철
    2009. 6. 30. 10:20 개발/JSP/Servlet

    Apache 와 Tomcat 을 연동시 아파치에서는 정적인파일 (이미지, js, html 등등) 을 처리하게 하고 톰캣에서는 동적인 파일들을 처리하도록 하는것이 가장 중요한 포인트입니다.

    대용량 트래픽을 유발하는 서비스의 경우는 이미지 파일 이나, js 파일 등을 아래와 같이 서브 도메인으로 만들어서 물리적으로 다른서버에 두게 하는경우가 일반적인 적용 가능한 경우입니다.

    예) 이미지, js 파일 등등 -> img.onjava.co.kr  (일반적으로 이미지 서버 또는 파일서버)
         동적인 파일             -> www.onjava.co.kr (웹서버)
         www.onjava.co.kr 내의 html 에서 img 를 호출시 <img src="http://img.onjava.co.kr/xxx/xx.jpg"> 와 같은 형태로
         처리.


    하지만, 비용적인 측면이나 많은 트래픽이 생기지 않는 웹서버의 경우에는 하나의 물리적인 서버에서 아파치와 톰캣의 역할을 적절하게 나눠서 운영한다면 효과적인 서버운영을 할수가 있습니다.


    1. 아파치 WebRoot가 /usr/local/apache/htdocs 이고,
        톰캣 WebRoot 가 /home/web/source/onjava/WebRoot 인 
    경우
        
        - 톰캣에서는 파일 확장자가 jsp인 파일만 처리하도록 

        - 아파치에서는 jsp 파일 외의 파일들 (이미지 파일, html 파일 등등) 을 처리하도록 하기 위해서 아래와 같이 설정해준다.
       
        httpd.conf 파일내에서 
      ---------------------------------------------------------------------------------------------------------------------------------------------------------------     
      DocumentRoot "/usr/local/apache/htdocs"
        
      <Directory "/usr/local/apache/htdocs">
        #
        # Possible values for the Options directive are "None", "All",
        # or any combination of:
        #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
        #
        # Note that "MultiViews" must be named *explicitly* --- "Options All"
        # doesn't give it to you.
        #
        # The Options directive is both complicated and important.  Please see
        # http://httpd.apache.org/docs/2.2/mod/core.html#options
        # for more information.
        #
         Options FollowSymLinks

        #
        # AllowOverride controls what directives may be placed in .htaccess files.
        # It can be "All", "None", or any combination of the keywords:
        #   Options FileInfo AuthConfig Limit
        #
         AllowOverride None

        #
        # Controls who can get stuff from this server.
        #
         Order allow,deny
         Allow from all

    </Directory>

    # 아래와 같이 WebRoot 경로를 하나더 추가해 준다.

    <Directory "/home/web/source/onjava/WebRoot">
        #
        # Possible values for the Options directive are "None", "All",
        # or any combination of:
        #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
        #
        # Note that "MultiViews" must be named *explicitly* --- "Options All"
        # doesn't give it to you.
        #
        # The Options directive is both complicated and important.  Please see
        #
    http://httpd.apache.org/docs/2.2/mod/core.html#options
        # for more information.
        #
         Options FollowSymLinks

        #
        # AllowOverride controls what directives may be placed in .htaccess files.
        # It can be "All", "None", or any combination of the keywords:
        #   Options FileInfo AuthConfig Limit
        #
         AllowOverride None

        #
        # Controls who can get stuff from this server.
        #
         Order allow,deny
         Allow from all

    </Directory>

    # 톰캣과 연동을 위한 추가 소스 부분 (httpd.conf 파일의 맨 마지막 부분에 추가)

    <IfModule mod_jk.c>
      JkWorkersFile "/usr/local/apache/conf/workers.properties"
    </IfModule>

    # mod_jk.so 파일은 아파치사이트에서 다운받으면 된다.
    LoadModule jk_module "/usr/local/apache/modules/mod_jk.so" 

    #Configure mod_jk

    JkWorkersFile conf/workers.properties
    JkLogFile logs/mod_jk.log
    JkLogLevel info

    JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "

    JkRequestLogFormat "%w %V %T"

    #Root context

    JkMount /*.jsp ajp13           -> 톰캣에서는 jsp 만 처리한다. (JkMount 에 추가된 파일만이 톰캣에서 처리하게 된다)
    #JkMount /*.html ajp13           -> 주석처리된 부분들은 모두 아파치에서 처리하게 된다.
    #JkMount /*.js ajp13
    #JkMount /*.jpg ajp13
    #JkMount /*.gif ajp13
    #JkMount /*.jpeg ajp13

    AddDefaultCharset UTF-8

    ----------------------------------------------------------------------------------------------------------------
    workers.properties 파일
        workers.tomcat_home=/usr/local/tomcat
        workers.java_home=/usr/local/java
        ps=\
        worker.list=ajp13
        worker.ajp13.port=8009
        worker.ajp13.host=localhost
     


    2. 위의 설정후에 jsp 파일이외의 이미지, html, js 파일 등은 /usr/local/apache/htdocs 에 위치시켜야 제대로 서비스가 가능하다. 당연히 톰캣에서 처리해야할 jsp 파일들은
    /home/web/source/onjava/WebRoot 에 위치시키면 된다.

    posted by 좋은느낌/원철
    2009. 6. 29. 16:35 개발/JSP/Servlet

    Apache 설정 및 톰캣 연동

    1. 아파치, 톰캣 설치

    1.1 윈도우에서 설치

    Tomcat 설치

    Apache 설치

    mod_jk 다운로드

    1.2 리눅스에서 설치

    리눅스 아파치 설치

    linux 에서 mod_jk 생성

    2. 아파치, 톰캣 연동

    참고1. server.xml의 구조
    <Server>
          |     
          +---<Service>
                      |
                      +---<Connector>
                      |
                      +---<Engine>
                                  |
                                  +---<DefaultContext>
                                  |
                                  +---<Realm>
                                  |
                                  +---<Logger>
                                  |
                                  +---<Host>
                                              |
                                              +---<Context>
                                              |
                                              +---<Value>
                                              |
                                              +---<Realm>
                                              |
                                              +---<Logger>
    

    2.1 Tomcat Connectors 복사

    • 다운로드한 mod_jk(mod_jk.so)파일을 %APACHE_HOME%/modules 안에 복사한다.

    2.2 workers.properties 파일 설정

    참고2. Tomcat Worker
    • 톰캣 워커는(Tomcat worker) 웹서버로부터의 서블릿 요청을 톰캣 프로세스(Worker)에게 전달하여 요청을 처리하는 톰캣 인스턴스이다.
    • 대부분 하나의 worker를 사용하나, load 밸런싱이나 site 파티셔닝을 위해 여러개의 worker를 사용 할 수 있다.
    • 서로 다른 톰캣 워커에 의해 서로 다른 context를 서비스 할 수 있다.
    • 워커 타입에는 ajp12, ajp13, jni, lb 등이 있다.
    • http://tomcat.apache.org/connectors-doc/reference/workers.html
    • apache와 tomcat를 연동하기위해서는 workers.properties 파일을 설정해야 한다.
    • %APACHE_HOME%/conf/workers.properties
    workers.properties 예제
    workers.tomcat_home=D:\tomcat5.5
    workers.java_home=C:\jdk1.5
    ps=/
    
    worker.list=oracleclub, wiki, dev
    
    #local.oracleclub.com
    worker.oracleclub.port=7003
    worker.oracleclub.host=localhost
    worker.oracleclub.type=ajp13
    
    #wiki.oracleclub.com
    worker.wiki.port=7004
    worker.wiki.host=localhost
    worker.wiki.type=ajp13
    
    #dev.oracleclub.com
    worker.dev.port=7005
    worker.dev.host=localhost
    worker.dev.type=ajp13
    
    참고3. 톰캣의 <Connector> 요소
    • 사용자의 요청을 <Engine>에 보내주는 역할을 하는것이 <Connector>이다. <Service>는 하나 이상의 <Connector>를 가져야 한다.
    • 사용자는 HTTP 또는 HTTPS/SSL등 여러가지 방법으로 <Engine>에 요청을 보내는데, 이들의 접속 처리는 <Connector>에 맡겨진다.
    • 각 프로토콜에 대해 복수의 <Connector>를 가지며, 어떤 요청이 와도 <Engine>이 동일하게 처리하고, 응답을 <Connector>에 맡길 수 있다.

    2.3 httpd.conf 파일 설정

    • %APACHE_HOME%/conf/httpd.conf 파일을 수정
      • jk_module 추가
      • workers.properties 파일 추가
      • virtualhost 설정 추가 (이 문서에서는 "conf/vhosts/*.conf" 파일로 추가 하였음)
    httpd.conf
    # jk_module 추가
    LoadModule jk_module modules/mod_jk-apache-2.0.58.so
    
    # workers.properties 파일 추가
    JkWorkersFile "C:\Program Files\Apache Group\Apache2\conf\workers.properties"
    
    # virtualhost 설정 추가 
    include "conf/vhosts/*.conf"
    

    2.4 가상 호스트 설정

    • %APACHE_HOME%/conf/vhosts/dev.conf 파일을 생성 한 후 아래의 내용을 추가한다.
    dev.conf
    <VirtualHost 127.0.0.1:80>
      ServerName dev.oracleclub.com
      ServerAlias oracleclub.com
      ServerAlias web.oracleclub.com
    
      DocumentRoot C:\struts2\webapp
        
      ErrorLog logs/dev.oracleclub.com-error.log
      CustomLog logs/dev.oracleclub.com-access.log common
    
      JkMount /*.ok  dev
    </VirtualHost>
    
    • mod_jk의 JkMount 지시자를 사용해 지정된 URL 들을 Tomcat으로 할당할 수 있다.
    • JkMount /*.ok dev URI에 .ok로 오는 요청은 workers.properties에 설정된 dev worker로 보낸다.

    2.5 톰캣 server.xml 파일 수정

    • workers.properties의 AJP/1.3 포트와 톰캣 Connector의 포트를 일치 시킨다.
    server.xml
     
     <?xml version="1.0" encoding="UTF-8"?>
    
    <Server port="20005" shutdown="SHUTDOWN">
      <Service name="Tomcat-Apache-mod_jk">
    
        <Connector port="7005"
                   enableLookups="false" redirectPort="10445" 
                   protocol="AJP/1.3" URIEncoding="euc-kr"  />
    
        <Engine name="webhosting" defaultHost="localhost">
    
          <Host name="dev.oracleclub.com" appBase="oracleclub"
           unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
           
          <Alias>oracleclub.com</Alias>
          <Alias>web.oracleclub.com</Alias>
    
           <Context path="" docBase="C:/struts2/webapp" reloadable="true" workDir="C:/struts2/webapp/WEB-INF/work" />
    
          </Host>
    
        </Engine>
    
      </Service>
    </Server>
    

    2.6 hosts 파일 변경

    • 127.0.0.1 dev.oracleclub.com

    3. 가상 호스트 예제

    하나의 IP로 여러개의 가상 호스트를 설정하는 방법을 알아보도록 하자.

    3.1 이름 기반 가상 호스트 설정

    • Apache는 HTTP의 Host 헤더를 이용하여 여러개의 호스트명을 하나의 IP 주소로 사용하는 것을 가능하게 한다.
    • httpd.conf파일에 NameVirtualHost 를 설정하여 이름기반의 가상 호스트를 사용 할 수 있다.(꼭 설정해야 함)
    • 아래 코드는 이름기반 가상 호스트 설정 예제이다.
    httpd.conf
    # 127.0.0.1에 연결되는 모든 요청을 Host 헤더의 내용을 기준으로 처리한다. 
    NameVirtualHost 127.0.0.1:80
    Listen 80
    
    <VirtualHost 127.0.0.1:80>
      ServerName dev.oracleclub.com
      DocumentRoot C:\struts2\webapp
    </VirtualHost>
    
    <VirtualHost 127.0.0.1:80>
      ServerName local.oracleclub.com
      DocumentRoot C:\oracleclub\webapp
    </VirtualHost>
    
    <VirtualHost 127.0.0.1:80>
      ServerName wiki.oracleclub.com
      DocumentRoot D:\confluence-2.7-std\confluence
    </VirtualHost>
    
    

    3.2 IP 기반 가상 호스트 설정

    • 각 호스트별로 하나의 IP 주소를 할당하는 방법.
    httpd.conf
     
     Listen 192.168.1.1:80
     Listen 192.168.1.2:80
    
    <VirtualHost 192.168.1.1:80>
      DocumentRoot C:\struts2\webapp
    </VirtualHost>
    
    <VirtualHost 192.168.1.2:80>
      DocumentRoot C:\oracleclub\webapp
    </VirtualHost> 
    

    4. Rewrite Rule

    • mod_rewrite module은 주소 재작성 패턴을 URL에 적용한다.
    • 패턴은 정규 표현식(regular expression)을 의미하며 이 정규식에 match가 되는 pattern을 요청한 url에서 출력 하게 된다.

    4.1 mod_rewrite 설치

    • apache 설치시 Configure 실행시에 --enable-rewrite 옵션을 추가한다.
    • apache 설치 이후 추가 설치시
      • 아파치 압축 푼 디렉토리로 이동 : cd /usr/local/httpd-2.0.63/modules/mappers
      • apxs를 이용해 새 모듈 추가 : /usr/local/apache2/bin/apxs -aic mod_rewrite.c

    4.2 Rewrite 모듈 지시자

    RewriteEngine

    • Rewriteing 엔진을 사용할지 여부를 설정
    • 디폴트 설정은 Off, RewriteEngine On 으로 설정하지 않는 이상 Rewritng 엔진을 사용할 수 없다.
    • 설정문법 : RewriteEngine On|Off

    RewriteRule

    • Rewrite 모듈의 실질적인 Rewrite 규칙들을 적용 한다.
    • Input URL을 Return URL로 변경하기 위한 규칙들을 설정 한다.
    • 아래는 RewriteRule을 이용해 퍼머링크를 만드는 예제다.
     <IfModule mod_rewrite.c>  
      RewriteEngine On
      RewriteRule ^/$ /main.ok [R]  
      RewriteRule ^/community/([0-9]+)$ /articlelist.ok?article.communityId=$1 [PT]
      RewriteRule ^/article/([0-9]+)$  /articleview.ok?article.articleId=$1 [PT]
    </IfModule>
    
    
    • RewriteRule 플래그
      • F(forbidden) : 요청하는 페이지를 403 에러로 redirect 시킵니다.
      • G(gone) : 요청하는 페이지를 410 에러로 redirect 시킵니다.
      • R(redirect) : Return URL로 redirect 한다.
      • PT(passthrough) : Input URL을 그대로 유지하며 Return URL을 실행한다.
      • http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

    RewriteCond

    참고4. 정규표현식 기초
    . : 다수의 한문자
    ? : 0개 이상의 한문자
    * : 0개 이상의 문자 또는 문자열
    + : 1개 이상의 문자 또는 문자열
    ^ : 문자열의 첫문(열)을 지정합니다.
    $ : 문자열의 끝 문자(열)을 지정합니다.
    (역슬래쉬) : 정규표현식에서 특별한 의미로 사용되는 문자의 특수기능을 제거합니다.(예:(, ), [, ] . 등)
    {n} : 정확히 n번 반복
    {n,} : n번 이상 반복
    {n,m} : n 이상 m 이하 반복
    [chars] : 문자들의 범위 또는 표현할 수 있는 문자들을 설정합니다.
    예) [a-z] : a 부터 z 까지의 소문자, [tT] : 소문자 t 또는 대문자 T
    
     정규표현식 단축표현들
    [:alpha:] : 알파벳. [a-zA-Z] 와 같은 표현
    [:alnum:] : 알파벳과 숫자. [a-zA-Z0-9] 와 같은 표현
    [:digit:] : 숫자 [0-9] 와 같은 표현
    [:upper:] : 대문자. [A-Z] 와 같은 표현
    

    5. 데모 및 실습

    문서에 대하여


    # 이 문서는 오라클클럽에서 작성하였습니다.
    # 이 문서를 다른 블로그나 홈페이지에 게재하실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^
    # 출처 : http://wiki.oracleclub.com/pages/viewpage.action?pageId=1507883&
    posted by 좋은느낌/원철
    2009. 6. 29. 16:20 개발/JSP/Servlet

     1  Apache 2.0
    http://httpd.apache.org 에서 httpd-2.0.49.tar.gz 받아서 푼다.


    $ tar xvfz httpd-2.0.49.tar.gz


    INSTALL 파일을 참고하여 apache를 설치하고 실행한다.


    $ ./configure --prefix=PREFIX $ make $ make install $ PREFIX/bin/apachectl start
    여기서 PREFIX는 apache가 설치될 디렉토리이다. --prefix=PREFIX를 생략하면 /usr/local/apache2에 설치된다.
    2003년경의 모 아티클에는 아파치 인스톨시에 configure --prefix=/usr/local/apache --enable-module=so 와 같이
    모듈 옵션을 주라고 하는데 최근 문서로 확인 해 봐야 할 듯.


    이하의 설명에서 PREFIX는 아파치가 설치된 디렉토리를 뜻한다.

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

    브라우저를 열고 http://127.0.0.1/을 입력하였을 때, apache web server가 설치되었다는 메시지가 나오면 성공.


    아파치 서버를 끝내려면


    $ PREFIX/bin/apachectl stop
    2 J2SE
    http://java.sun.com에서 J2SE 1.4.2 를 받아 설치한다. SDK를 받아야 된다. JRE만 받으면 안 됨.


    확장자가 bin인데 실행권한을 주고 실행시키면 license에 동의하는지를 묻고 이에 대하여 y를 눌러 대답하면 설치가 된다.


    아래와 같이 심볼릭 링크를 한다.


    $ ln -s /usr/java/j2sdk1.4.2_04 /usr/local/java

    /etc/profile.d/java.sh를 아래의 내용으로 만들어 넣는다. (실행 퍼미션으로 넣어야 한다.)


    JAVA_HOME=/usr/local/java export JAVA_HOME

    3  Tomcat 5
    http://jakarta.apache.org에서 jakarta-tomcat-5.0.19.tar.gz를 받아서 푼다. (5.5.x 버전도 잘 동작함을 확인 함.)

    $ tar xvfz jakarta-tomcat-5.0.19.tar.gz

    RUNNING.txt 파일을 참고하여 tomcat을 실행시킨다.

    $ $CATALINA_HOME/bin/startup.sh여기서 $CATALINA_HOME은 tomcat이 설치된 디렉토리이다.


    아래와 같이 심볼릭 링크를 한다.

    $ ln -s /usr/jakarta-tomcat-5.0.19 /usr/local/tomcat

    브라우저를 열고 http://127.0.0.1:8080/을 입력하였을 때, tomcat이 설치되었다는 메시지가 나오면 성공. tomcat을 끝내려면

    $ $CATALINA_HOME/bin/shutdown.sh

    4  mod_jk2.so


    http://jakarta.apache.org 에서 jakarta-tomcat-connectors-jk2-src-current.tar.gz를 받아서 푼다.


    jk/native2/INSTALL.txt를 참고하여 mod_jk2.so를 만든다.

    $ ./configure --with-apxs2=PREFIX/bin/apxs $ make $ cd ../build/jk2/apache2 $ PREFIX/bin/apxs -n jk2 -i mod_jk2.so* PREFIX는 apache가 설치된 경로로 대개 /usr/local/apache 혹은 /usr/local/apache2 에 위치한다.

     

    5  httpd.conf
    위에서 만든 mod_jk2.so를 PREFIX/modules/에 복사한 다음, PREFIX/conf/httpd.conf 에서

    #LoadModule foo_module modules/mod_foo.so
     와 같은 형식으로 되어 있는 곳을 찾아 그 아래에

    LoadModule jk2_module modules/mod_jk2.so
    를 추가한다.


    DirectoryIndex를 찾아 그 줄에 index.jsp를 추가한다.

    Alias /icons/ "/usr/local/apache2/icons/"와 같은 형식의 행을 찾아 그 아래에

    Alias /jsp-examples/ "/usr/local/tomcat/webapps/jsp-examples/" Alias /servlets-examples/ "/usr/local/tomcat/webapps/servlets-examples/"
    를 추가한다.


    DocumentRoot 행을 찾아

    DocumentRoot "/www"
    로 바꾸고 저장하고 아래와 같이 심볼릭 링크를 한다.

    $ ln -s /usr/jakarta-tomcat-5.0.19/webapps/ROOT /www
    * 이렇게 아파치의 DocumentRoot 와 톰캣의 DocRoot를 바로 연결 하기보단 톰캣의 가상호스트 설정으로 돌리는 쪽이 훨씬
      나은 방법이라고 생각 함.
    *위 방법대로 설정 시 ContextRoot가 / 가 되는 것은 위에 설정한 톰캣 ROOT밖에 없다.
    *위 설명에서와 같이 아파치의 DocumentRoot 와 톰캣의 DocRoot 심볼릭 링크로 걸지 않고 톰캣의 Host설정만으로도 충분함.


    6 workers2.properties
    PREFIX/conf/에 workers2.properties를 아래의 내용으로 만들어 저장한다. ( jk/native2/INSTALL.txt 참고 )
    [channel.socket:localhost:8009] port=8009 host=127.0.0.1  [ajp13:localhost:8009] channel=channel.socket:localhost:8009  [uri:/*.jsp] worker=ajp13:localhost:8009  [uri:/servlets-examples/*] worker=ajp13:localhost:8009
    * 위 5번 httpd.conf 수정시 제 방식대로(아파치 DocumentRoot와 톰캣의 ROOT를 심볼릭으로 엮지않는 방법) 톰캣의 HOST를
    설정하는 방식을 따른다면 아래의 내용을 추가하여 모든 uri에 대해 톰켓이 알 수 있도록 다음을 추가 합니다.

    [uri:/*] worker=ajp13:localhost:8009
     

     

    7  Virtual Host
    # Virtual Host의 경우 아래 URI에서 호스트 명을 넣어야 하고요. server.xml에서 host명을 넣으시면 됩니다.
    [uri:www.kldp.net/*.jsp] worker=ajp13:localhost:8009  [uri:www.kldp.net/servlets-examples/*] worker=ajp13:localhost:8009  [uri:www.kldp.org/*] worker=ajp13:localhost:8009

    8  LB(로드 발란서)
    -- :> 내일 올릴게요.


    9  apache 실행
    $ PREFIX/bin/apachectl start

    10  tomcat 실행
    $ $CATALINA_HOME/bin/startup.sh  또는  $ $CATALINA_HOME/bin/catalina.sh start

    11  확인
    브라우저에서 http://127.0.0.1을 입력하면 톰캣 화면이 나온다. (8080을 입력하지 않은 것을 주목)


    http://127.0.0.1/jsp-examples/을 입력하여 그곳에 있는 jsp 예제를 클릭하여 실행결과가 나타나면 jsp 성공.


    http://127.0.0.1/servlets-examples/를 입력하여 그곳에 있는 servlet 예제를 클릭하여 실행결과가 나타나면 servlet 성공.
    2008/03/07 01:26 2008/03/07 01:26 
     

    posted by 좋은느낌/원철
    2009. 2. 24. 17:00 개발/JSP/Servlet

    출처 : http://www.potatosoft.com/tt/218

    Java 를 기반으로 구현된 모든 코드에서 국제화 등을 이유로 리소스 파일 작성을 할때에, 문자열 등의 리소스 파일은 ascii 값의 ISO-8859-1 인코딩으로 작성해 주어야 합니다.

    프로퍼티 파일들을 UTF-8 로 읽어주도록 변경되면 좋겠지만 어쨌든 현재는 그렇습니다.

    이 때문에 jdk 에는 native2ascii 라는 실행파일이 들어 있는데( $JAVA_HOME/bin 에 들어있음 ) 이놈을 이용해서 프로퍼티 파일을 파라메터로 건내주거나 파일 실행 후 문자열을 입력해보면 Latin-1 인코딩의 ascii 값을 알 수 있습니다.

    ANT에서도 native2ascii task 를 지원하기 때문에 일반적으로 컴파일 및 빌드 과정과는 별개로 native2ascii 를 이용해서 리소스 파일들을 바꾸어 주는 작업을 추가하게 됩니다.

    Quick and Dirty Hack for UTF-8 Support in ResourceBundle 라는 포스팅을 보면 PropertyResourceBundle 의 wrapper class 구현이 있는데 이런 걸 이용하는 것이 편하긴 합니다. 다만 해당 포스팅의 아래쪽 comment 를 보면 3가지 정도의 bug case 에 대한 지적이 있는데 특히 Brian 이 지적한 내용은 반드시 적용해서 사용하셔야겠습니다.

    Very cool however I found a bug in your impl. when asking for a resource bundle with a parent. This is how I fixed it. Notice the call to getString which makes sure to recursively go over the parent bundles. Also checking for null.

    protected Object handleGetObject(String key) {
        String value = (String)bundle.getString(key);
        if (value==null) return null;
        try {
            return new String (value.getBytes("ISO-8859-1"),"UTF-8") ;
        } catch (UnsupportedEncodingException e) {
        // Shouldn't fail - but should we still add logging message?
        return null;
        }
    }

    And another small thing: not all ISO-8859-1 chars are a subset of UTF-8. The (C) sign seems to clash. If I put a \u00a9 in a UTF-8 file, it fails. But if I put the actual sign, it works. For some reason it is encoded as two bytes even though it is below 192 decimal.

    Not a big deal though. Still very cool solution.

    첫번째 지적한 경우에 해당하는 문자는 저작권 표시와 유로화 표시, 그리고 무한대 표시 등이 있는 것 같네요.


    이런 프로그래밍적인 것 말고 이클립스 플러그인 형태의 '편집기'를 원하는 분이라면 Properties Editor 라는 것을 추천합니다.

    이클립스의 Help -> software updates -> add site 를 선택하고 http://propedit.sourceforge.jp/eclipse/updates/ 를 추가해서 업데이트를 하면 됩니다.

    설치를 하고 나서 파일을 생성할때 확장자를 .properties 로 설정하면 해당 파일을 편집할때 자동으로 이 Properties Editor 를 이용해서 편집이 되고 properties 파일의 아이콘도 에디터 설치 후에는 아래와 같이 녹색 P 모양으로 바뀌게 됩니다.

    image

    물론 파일을 선택하고 팝업메뉴를 띄워서 Open with... 로 파일을 열 수도 있습니다.

    package.properties 파일을 열어보면 이렇게 이쁘게 한글로 표시가 되어 있습니다...만...

    image

    Open with 를 선택하고 일반 텍스트 편집기로 열어보면

    image

    native2ascii 를 돌린 것처럼 이쁘게 변환되어 있습니다. 전체 프로젝트의 인코딩이 UTF-8로 지정되어 있어도 해당 .properties 파일은 ISO-8859-1 로 맞춰지기 때문에 별도로 파일 인코딩을 바꾸어주지 않아도 되니 편리하군요.

    posted by 좋은느낌/원철
    2008. 7. 1. 20:24 개발/JSP/Servlet
    쿠키 유틸리티 클래스 CookieUtil 만들기

    쿠키는 웹 어플리케이션에서 클라이언트의 정보를 임시로 저장하기 위해 많이 사용된다. 또한, 클라이언트의 상태를 유지할 때 사용되는 세션을 구현하기 위해 쿠키를 사용하기도 한다. 쿠키는 약방의 감초와 같은 존재로서, 쿠키를 사용함으로써 좀더 쉽고 간결한 방법으로 웹 어플리케이션을 구현할 수 있게 되는 경우가 많다.

    쿠키가 사용되는 부분은 많은데, 서블릿 API의 쿠키 지원 클래스는 2.4 버전이 나올 때 까지 여전히 빈약하다. 서블릿 API의 javax.servlet.http.HttpServletRequest 인터페이스가 제공하는 쿠키 관련 메소드는 아래에 표시한 한개뿐이다.

       public Cookie[] getCookies()
    
    

    HttpServletRequest 인터페이스가 쿠키 관련된 메소드를 빈약하게 제공하기 때문에(진짜 심하게 빈약함이 느껴진다!!), JSP나 서블릿 등에서 쿠키를 사용할 때에는 쿠키를 다루기 위한 보조 클래스를 작성해서 작업하는 것이 좋다. 본 글에서는 편리하게 쿠키를 처리할 수 있도록 해 주는 CookieBox 라는 클래스를 작성해볼 것이다.

    CookieBox 클래스의 소스 코드

    말보다는 소스 코드를 직접 보면서 설명하는 것이 이해가 빠를 것 같으므로, CookieBox 클래스의 소스 코드부터 살펴보도록 하자.

        package jsp.util;
        
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.Cookie;
        import java.util.Map;
        import java.net.URLEncoder; 
        import java.net.URLDecoder; 
        import java.io.IOException; 
        
        public class CookieUtil {
            
            private Map cookieMap = new java.util.HashMap();
            
            public CookieUtil (HttpServletRequest request) {
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (int i = 0 ; i < cookies.length ; i++) {
                        cookieMap.put(cookies[i].getName(), cookies[i]);
                    }
                }
            }
            
            public static Cookie createCookie(String name, String value)
            throws IOException {
                return new Cookie(name, URLEncoder.encode(value, "euc-kr"));
            }
        
            public static Cookie createCookie(
                    String name, String value, String path, int maxAge) 
            throws IOException {
                Cookie cookie = new Cookie(name, 
                                        URLEncoder.encode(value, "euc-kr"));
                cookie.setPath(path);
                cookie.setMaxAge(maxAge);
                return cookie;
            }
            
            public static Cookie createCookie(
                    String name, String value,  
                    String domain, String path, int maxAge) 
            throws IOException {
                Cookie cookie = new Cookie(name, 
                          URLEncoder.encode(value, "euc-kr"));
                cookie.setDomain(domain);
                cookie.setPath(path);
                cookie.setMaxAge(maxAge);
                return cookie;
            }
            
            public Cookie getCookie(String name) {
                return (Cookie)cookieMap.get(name); 
            }
            
            public String getValue(String name) throws IOException {
                Cookie cookie = (Cookie)cookieMap.get(name);
                if (cookie == null) return null;
                return URLDecoder.decode(cookie.getValue(), "euc-kr");
            }
            
            public boolean exists(String name) {
                return cookieMap.get(name) != null;
            }
        }
    
    

    CookieBox 클래스는 다음과 같이 두 가지 종류의 메소드를 제공한다.

    • Cookie 객체를 생성할 때 사용할 수 있는 static 메소드인 createCookie()
    • HttpServletRequest의 Cookie 객체 및 쿠키값을 읽어올 수 있는 메소드

    CookieUtil 클래스를 이용한 쿠키값 읽기

    먼저, CookieUtil 클래스를 사용하면 손쉽게 쿠키를 사용할 수 있다. CookieUtil 는 다음과 같은 형태로 사용할 수 있다.

        
        // CookieUtil 클래스의 생성자는 request로부터 쿠키 정보를 추출
        CookieUtil cookie = new CookieUtil(request);
        
        Cookie idCookie = cookie.getCookie("id"); // 쿠키가 존재하지 않으면 null 리턴
        
        // 지정한 이름의 쿠키가 존재하는지의 여부
        if (cookieBox.exists("name")) {
            ...
        }
        
        // 지정한 이름의 쿠키가 존재하지 않으면 값으로 null 리턴
        String value = cookie.getValue("ROLE");
    
    

    일단 CookieBox 객체를 생성한 이후에는 세 개의 메소드(getCookie(), exists(), getValue())를 사용해서 손쉽게 Cookie 객체 및 쿠키값을 사용할 수 있게 된다. 별도의 유틸리티 클래스를 사용하지 않고 쿠키를 사용할 때는 다음과 같은 방식을 사용하게 되는데, 아래 코드와 비교하면 얼마나 위 코드가 간단한 형태인지를 알 수 있을 것이다.

        Cookie[] cookies = request.getCookies();
        Cookie idCookie = null;
        
        if (cookies != null) {
            for (int i = 0 ; i < cookies.length ; i++) {
                if (cookies[i].getName().compareTo("id") == 0) {
                    idCookie = cookies[i];
                }
            }
        }
        
    

    CookieUtil 클래스를 이용한 Cookie 생성

    javax.servlet.http.Cookie 클래스가 제공하는 생성자는 다음과 같이 한개 뿐이기 때문에,

        Cookie(java.lang.String name, java.lang.String value)
    
    

    쿠키에 대한 도메인, 경로, 유효시간 등을 설정하기 위해서는 다음과 같은 코드를 사용해야 한다.

        Cookie cookie = new Cookie(name, URLEncoder.encode(value, "euc-kr"));
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
    
    

    CookieBox 클래스는 static 메소드인 createCookie() 메소드를 통해서 적은 코딩량으로 손쉽게 Cookie 객체를 생성할 수 있도록 지원한다. 예를 들어, CookieBox.createCookie() 메소드를 사용하면 위 코드를 다음과 같이 한줄로 변경할 수 있다.

        Cookie cookie = CookieUtil.createCookie(name, value, domain, path, maxAge);
    
    

    CookieUtil.createCookie() 메소드가 세 가지 형태로 존재하기 때문에, 그때 그때 알맞은 메소드를 사용해서 Cookie 객체를 생성할 수 있을 것이다.

    프로바이더 최범균 ( madvirus@madvirus.net ) :
    JSP Professional, JSP 실전 Know-how, Jakarta Project 등의 책을 집필하였으며, 자바캔의 운영자로도 활동하고 있다. 현재 CVNet e-biz 팀에서 근무하고 있다.
    posted by 좋은느낌/원철
    2008. 6. 29. 22:34 개발/JSP/Servlet

    In this article I will show up how to setup a DataSource on Websphere 6.1 for MySQL step by step.

    After you read this article, you will be capable to create a DataSource on Websphere 6.1 using MySQL database. Also, this article can be useful if you want to use another database, such as DB2, Oracle and so on.

    Setting up a DataSource

    Basically, there are 3 steps to create a DataSource on Websphere:

    1. Create a JDBC Provider
    2. Create a J2C
    3. Create the DataSource

    Creating a JDBC Provider

    First of all, you must start the Websphere server and open its admin console: http://localhost:9060/ibm/console/. On Admin Console, expand the Resources -> JDBC section.

    Click on JDBC Provider link and a list of current JDBC providers will appears for you. By default, WAS 6.1 brings only Derby JDBC Provider already setup. We are going to create a new one for MySQL. Select the Scope and then click on New.

    On the new screen, select User-Defined in Database type field (because WAS doesn’t have MySQL pre-defined), com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource in Implementation Class Name field and MySQL JDBC Provider in Name field.

    After that, click on Next button. On next screen, you must inform the ClassPath of the JARs files. In my case, I copied the file mysql-connector-java-5.1.6-bin.jar to the <WAS-HOME>/lib directory.

    Click on Next and on the next screen click on Finish. The first screen will come up and then you must click on Save link to commit the information to Websphere.

    Creating a J2C

    J2C is a way to create an authentication for our DataSource. The easiest way to create it is go to Data Sources section, click on New and then click on the link create a new J2C authentication alias.

    On the new screen, click on New button and fill up the fields:

    Click on OK and then Save link.

    Creating the DataSource

    Go to Data Sources section and click on New. On the new screen, insert the Data source name, JNDI name and select the J2C.

    Note: The JNDI name default is jdbc/ plus JNDI name.

    On the next screen, select the JDBC Provider previously created.

    On the next two screens, just click on Next and then Finish. To commit the changes, click on Save link.

    We are almost done. We need now to setup a couple of parameters. To do that, click on your Data Source and onto the new screen, click on Custom properties link.

    On Custom properties, you must change the value to databaseName and serverName. (there are also other properties that you are free to change them if you want).

    After the changes are done, it is time to test the DataSource. Back to the Data sources section, check the datasource you want and click on Test connection button. A message should appears.

    We’re done! The DataSource has been created, tested and now it is ready to be used within Websphere Application Server v6.1

    Creating a Web Application to access the DataSource

    If you are using Websphere 6.1, probably you are using RAD 7 (Rational Application Developer) as well.

    First of all, you must create a Dynamic Project. Then go to Web perspective and select the menu New -> Dynamic Web Project. Insert a project name and click finish (for this example, you do not need to create an EAR project).

    The second step is to link the DataSource in our Web Project. To do that, simply open the Deployment Descriptor (double click on it).

    On the new screen, go to References section. There, click on Add button and then Resource reference. Fill up the fields like below:

    Back to the References section, click on the Reference just created and in the Websphere bindings, insert the JNDI name of the datasouce created into Websphere.

    After that, both files (web.xml and ibm-web-bnd.xmi) will be configured. Your web application can call the DataSource through the alias: jdbc/ApplicationDS.

    Below following a piece of code which uses the DataSource. This code can be used in a Servlet, JSP, ManagedBean and so on.

    1. try {  
    2.     Context ctx = new InitialContext();  
    3.     DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/ApplicationDS");  
    4.     Connection con = ds.getConnection();  
    5.     PreparedStatement query = con.prepareStatement("select * from customers");  
    6. } catch (Exception e) {  
    7.     e.printStackTrace();  
    8. }  

    Look at the line number 3, in this line we are calling the DataSource from Websphere.

    Conclusion

    I really hope this topic be useful for anyone else. It is a simple and fast way to create a DataSource (and use it) in Websphere 6.1 environment.

    Ads by Google
    Advanced WebSphere Tools
    Tooling/support for WS 5.1, 6.x No vendor lockin, only $149/year
    www.myeclipseide.com
    Java Database
    Pure Java database. Improve data access and increase profits. Try It
    www.progress.com/objectstore
    MS SQL Server 2005 Tools
    MS SQL Server Database Admin Tools Download Now! Windows, Linux, OSX
    www.aquafold.com
    WebSphere Management
    Manage performance of servers, EJBs Servlets, JVM, Web Application
    manageengine.adventnet.com/Download
    posted by 좋은느낌/원철
    prev 1 next