2013년 3월 20일 수요일

Tomcat URL 직접 접근 막기

o web.xml 설정


 <!-- Define a Security Constraint on this Application -->
 <security-constraint>
  <web-resource-collection>
   <web-resource-name>Resumes</web-resource-name>
   <url-pattern>/data/*</url-pattern>

   <url-pattern>/data2/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
   <!-- NOTE:  This role is not present in the default users file -->
   <role-name>admin</role-name>
  </auth-constraint>
 </security-constraint>

 <!-- Define the Login Configuration for this Application -->
 <login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>인증창에 설명할 내용</realm-name>
<!--  <auth-method>FORM</auth-method>
  <form-login-config>
   <form-login-page>/admin/login.jsp</form-login-page>
   <form-error-page>/admin/fail.jsp</form-error-page>
  </form-login-config> -->

 </login-config>

 <!-- Security roles referenced by this web application -->
 <security-role>
  <description>
  The role that is required to log in to the Manager Application
  </description>
  <role-name>admin</role-name>
 </security-role>

 

Tomcat 404 Error 처리

 

o 설정 내용

 1. {Context}/WEB-INF/web.xml 수정

 2. {docBase}/{errorHandlingDirectory}/{errorPage} 작성

    - Error Page의 기준 Path는 Context에 설정한 docBase가 되며,

       {errorHandlingDirectory}는 임의로 지정하면 된다.

 

1. 해당 Context의 WEB-INF에 있는 web.xml에 다음 추가

<web-app>

... ...

... ...

<error-page>
    <error-code>404</error-code>

    <location>/error/error404.jsp</location>

    <exception-type>java.lang.NullPointerException</exception-type>
    <location>/error/errorNullPointer.jsp</location>

</error-page>

<error-page>
    <error-code>500</error-code>
    <location>/error/500.jsp</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/error/exception.jsp</location>
</error-page>

<error-page>
    <exception-type>java.lang.NullPointerException</exception-type>
    <location>/servlet/ErrorServlet2</location>
</error-page>

... ...

... ...
</web-app>

2.해당 Context의 docBase에 Error Page 작성

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%

        Status를 200(OK)로 Response하지 않으면

        브라우져의 Default 404 Error Page가 뜨게 된다.
          response.setStatus( HttpServletResponse.SC_OK );
%>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>404 Error</title>
</head>

<body>
 <center><B>요청하신 Page를 찾을 수 없습니다.</B></center>
</body>
</html>

 

* 참고 사항

web.xml 의 <error-code>, <exception-type> 엘리먼트에 설정된 오류의 <location> 지정 서블릿/JSP 가 수행될 때 발생된 오류에 대한 정보가 HttpServletRequest 객체 통해 전달됨.

 

  - javax.servlet.error.status_code : 오류 코드

  - javax.servlet.error.exception_type : 예외 타입 정보 (Class 형 객체)

  - javax.servlet.error.message : 예외 메시지

  - javax.servlet.error.exception : 발생된 예외 객체

  - javax.servlet.error.request_uri : 오류 발생 파일의 URI

 

  ==> 사용법

        Object exObj = req.getAttribute("javax.servlet.error.exception");

        String uri = "";

        if(uriObj != null)   uri= uriObj.toString();

==========================================================================
out.print(request.getAttribute("javax.servlet.error.status_code"));
out.print("<br/>");
out.print(request.getAttribute("javax.servlet.error.exception_type"));
out.print("<br/>");
out.print(request.getAttribute("javax.servlet.error.message"));
out.print("<br/>");
out.print(request.getAttribute("javax.servlet.error.exception"));
out.print("<br/>");
out.print(request.getAttribute("javax.servlet.error.request_uri"));
 

CVS 설치 및 설정

CVS(Concurrent Version System)

 

  1. 설치 확인

    RPM으로 설치된 package가 있는지 확인한다.

    $ rpm -qa | grep cvs

    Package가 있다면 다음과 같이 설치한다.

    $ rpm -Uvh cvs-version.rpm

          또는

    $ rpm -ivh cvs-version.rpm

 

  2. Download & 설치

    Download here: http://www.nongnu.org/cvs/

    $ ./configure

    $ make

    $ make install

 

  3. 설정(초기화)

     '/home/cvsroot'에 원하는 cvs의 repositary path를 입력한다.

    $ cvs -d /home/cvsroot init

             또는

    환경변수 CVSROOT=/home/cvsroot를 profile파일에 설정하고

    $ cvs init

Apache HTTP Server 2.2.4 + Apache Tomcat 5.5.23 + Tomcat Connector 1.2.25(mod_jk) 설치 및 연동

mod_jk를 사용해서 아파치 2 와 톰캣 5.5를 연동하기 

1: 아파치 2를 설치한다.

httpd-2.0.55의 소스를 받아 설치한다.
./configure --enable-so --enable-mods-shared=most --prefix=/opt/httpd-2.2.4
make
make install

2: 자바(JDK 1.5이상)를 설치한다.

/usr/local/java 등의 위치에 설치하고, /etc/profile 제일 아랫줄에
export JAVA_HOME=/usr/java/jdk1.5.0_05
라고 추가하고,
source /etc/profile 명령을 실행해서 변경을 적용시킨다.


3: 톰캣 5.5 설치

apache-tomcat-5.5.12.tar.gz 를 다운받아 /usr/local 에 놓고 root 권한으로 아래와 같이 실행한다.

cd /usr/local
tar xvfz apache-tomcat-5.5.12
ln -s /opt/apache-tomcat-5.5.23 /opt/tomcat
groupadd tomcat
useradd tomcat -g tomcat -d /opt/tomcat tomcat
chown -R tomcat.tomcat /opt/apache-tomcat-5.5.12 /opt/tomcat

/etc/profile에 아래의 내용을 추가하고 적용한다.

export PATH=$PATH:/usr/local/bin:/opt/tomcat/bin
export JAVA_HOME=/usr/java/jdk1.5.0_05
export CATALINA_HOME=/opt/tomcat

위의 내용을 추가했으면,

source /usr/profile을 실행


톰캣 서버 실행 테스트

톰캣 디렉토리의 bin디렉토리가 PATH에 포함된 것을 확인하고,
startup.sh
을 실행하면 톰캣이 실행된다.

ps -def | grep tomcat
이라고 실행할 때
tomcat 18591 1 88 06:40 pts/0
와 비슷한 내용이 보이면 톰캣 서버가 실행된 것이다.
 
shutdown.sh
을 실행하여 톰캣 서버를 멈추고서, 다시
ps -def | grep tomcat

을 실행하면 위의 내용이 보이지 않게 된다.


4: mod_jk 설치하기
 jakarta-tomcat-connectors-1.2.14.1-src.tar.gz 를 다운받고 아래처럼 실행한다.

cd tomcat-connectors-1.2.25-src/native
./buildconf.sh
./configure --with-apxs=/opt/httpd-2.2.4/bin/apxs
make

make install

mod_jk.so 가 /opt/httpd-2.2.4/modules 디렉토리 안에 있고, 권한은 755로 설정되어있는지 확인한다.

 

5: 아파치를 톰캣에 연결하기

/usr/local/apache2/conf 디렉토리에 workers.properties 라는 이름의 파일을 만들고 아래의 내용을 입력한 후 저장한다.

workers.tomcat_home=/opt/apache-tomcat-5.5.23
workers.java_home=/opt/java
ps=/
worker.list=ajp13

worker.ajp13.port=8009
worker.ajp13.host=[ localhost | IP ]
worker.ajp13.type=ajp13

 

httpd.conf 에 아래의 내용을 추가한다.
# Mod_jk settings
# Load mod_jk module
LoadModule jk_module modules/mod_jk.so
# Where to find workers.properties
JkWorkersFile conf/workers.properties
# Where to put jk logs
JkLogFile logs/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel debug
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"

iBATIS 오류 Cause: java.lang.IllegalArgumentException: Cannot subclass final class int



iBATIS Error Cause: java.lang.IllegalArgumentException: Cannot subclass final class int

Cause: java.lang.IllegalArgumentException: Cannot subclass final class int


Solution>

Add attribute at 'settings' tag in your SQL map config file, like below...
enhancementEnabled="false"
...
/>

iBATIS Insert 시 자동으로 생성된 Key의 참조


MySQL 사용 시 예제

<insert ...>

<!--

insert query here

-->

<selectKey keyProperty="createdKey" resultClass="int">

SELECT LAST_INSERT_ID()

</selectKey>

</insert>

DBMS 별 참조 Key

oracle: nextval(#sequence#)

mssql: @@IDENTITY

mysql: LAST_INSERT_ID()


30 Auto Completion Scripts for Better User Experience

http://www.1stwebdesigner.com/resources/auto-completion-scripts/

NoSuchProviderException: provider Cryptix is not available

 

Cryptix를 Library를 이용한 암/복호화 시 Tomcat과 연동할 때가 있을 수 있는데

이때 설정을 하지 않고 사용할 경우 발생하는 오류 되시겠다.

NoSuchProviderException: provider Cryptix is not available

 설정을 확인해야할 부분은 다음과 같다.

 

1. "$JAVA_HOME/lib/"에 cryptix32.jar Library를 복사한다.

2. 다음 명령을 실행해 Install한다.

   $ java -classpath cryptix32.jar cryptix.provider.Install

3. "$CATALINA_HOME/bin/"에 있는 catalina.sh을 수정한다.

   CLASSPATH=$JAVA_HOME/lib/cryptix32.jar:$CLASSPATH

4. Tomcat Restart

 

 

 

 

암호화/복호화


import java.security.*;
import javax.crypto.*;
public class SimpleExample {
    public static void main(String [] args) throws Exception {
        if( args.length != 1) {
            System.out.println("Usage : java SimpleExample text ");
            System.exit(1);
        }
        String text = args[0];
        System.out.println("Generating a DESded (TripleDES) key...");
        // Triple DES 생성
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(168); // 키의 크기를 168비트로 초기화
        Key key = keyGenerator.generateKey();
        System.out.println("키생성이 완료되었음");
        System.out.println("key=" + key);
        // Cipher를 생성, 사용할 키로 초기화
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte [] plainText = text.getBytes("UTF8");
        System.out.println("Plain Text : ");
        for (int i = 0; i < plainText.length ; i++) {
            System.out.print(plainText[i] + " ");
        }
        // 암호화 시작
        byte [] cipherText = cipher.doFinal(plainText);
        // 암호문서 출력
        System.out.println("\nCipher Text : ");
        for (int i = 0; i < cipherText.length ; i++) {
            System.out.print(cipherText[i] + " ");
        }
        //복호화 모드로서 다시 초기화
        cipher.init(Cipher.DECRYPT_MODE, key);
        //복호화 수행
        byte [] decryptedText = cipher.doFinal(cipherText);
        String output =  new String(decryptedText, "UTF8");
        System.out.println("\nDecrypted Text : " + output);
    }
}

MD5 암호화



import java.security.*;


public class MD5Password
  {
  public static String getEncodedPassword(String clearTextPassword)
               throws NoSuchAlgorithmException
    {
    MessageDigest md = MessageDigest.getInstance("MD5");

    md.update(clearTextPassword.getBytes());

    return HexString.bufferToHex(md.digest());
    }

  public static boolean testPassword(String clearTextTestPassword,
                     String encodedActualPassword)
                     throws NoSuchAlgorithmException
    {
    String encodedTestPassword = MD5Password.getEncodedPassword(
                      clearTextTestPassword);

    return (encodedTestPassword.equals(encodedActualPassword));
    }
  }