메뉴 건너뛰기

2017.03.11 00:49

tomcat - server.xml 설정

조회 수 99638 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

Apache Tomcat 개요

  • Apache Tomcat Server7
    • 최신 톰캣 7.0은 현재 서블릿 API 3.0의 레퍼런스 구현입니다
    • servlet 그리고 JSP 웹 어플리케이션을 구동하기 위해 java 기반으로 개발 되었다.
    • Tomcat  메이저 버전은  Java Servlet 명세서 버전에 따라 간다.
    • The Tomcat Manager Web Application
      • Tomcat 서버와 함께 패키징 되어 배포된다.
      • / conext path에 설치되어 배포되어 지며 웹 어플리케이션을 관리하기 위한 기본적인 기능을 제공한다.
    • Specialized Realm Implementations
      • realms?  컨테이너에 의해 인증되어진 사용자 데이터베이스를 relams라고 부른다.
      • 톰캣은 두가지 타입의 realms을 제공한다. MemoryRealm, JDBCRealm
    • Tomcat Valves
      • Tomcat은 밸브 톰캣 4 소개된 기술이며, 모든 이후 버전에서 사용할 수있는.
      • 밸브는 특정 카탈리 컨테이너와 자바 클래스의 인스턴스를 연결할 수 있습니다.
      • 구성된 밸브의 클래스는 다음 컨테이너에 오는 모든 요청을위한 전처 리기 역할을하고 있습니다.
    • The Architecture of Tomcat
      • 톰캣 인스턴스, 또는 서버는 톰캣의 컨테이너 계층 구조에서 최상위 요소입니다.
      • 오직 하나의 톰캣 인스턴스만이 하나의 자바 가상 머신 (JVM)에 살고 있습니다.
      • 이러한 접근 방식은 케이스 톰캣 및 / 또는 JVM 충돌 안전, Tomcat 서버와 동일한 물리적 머신에서 실행하는 다른 모든 Java 응용 프로그램을 만듭니다.
      • 톰캣 인스턴스는 잘 정의된 계층에 존재하는 응용 프로그램 컨테이너의 그룹화로 구성되어 있습니다.
      • 그 계층의 주요 구성 요소는 카탈리나의 서블릿 엔진입니다.
      • 자바 서블릿 API에 명시된대로 카탈리나는 실제 자바 서블릿 컨테이너의 구현입니다.
      • Tomcat은 7 서블릿 API 3.0 Sun에서 최신 사양을 구현합니다.
      • Tomcat7의 아키텍처는 아래 XML 구조와 일치 한다.

    • The Server

    그것은 전체 카탈리나의 서블릿 엔진을 상징하며 단일 톰캣 인스턴스의 최상위 요소로 사용됩니다.
    <server>를 요소는 하나 이상의 <Service> 컨테이너를 포함할 수 있습니다.

    • The Service

    단일 <Engine> 요소를 공유하는 하나 이상의 <Connector> 요소의 컬렉션을 보유하고 있다.
    N개의 <Service>엘리먼트는 단일 <Server> 엘리먼트 안에 중첩될 수 있다.

    • The Connector

    클라이언트으로 부터 호출 된 실제 request 및 response를 핸들링하는 클래스를 정의한다.

    • The Engine

    <Service> 는 오직 하나의  Engine를 가진다.

     단일 <Engine> 컴포넌트는 <connector>컴포넌트에서 수신받은 모든 요청을 처리한다.

    • The Host

    <Host> 요소는 카탈리나의 <Engine>의 각 인스턴스에 포함된 가상 호스트를 정의합니다.
    각 <Host>는 하나 이상의 웹 어플리케이션의 부모가 될수 있다.

    • The Context

    <Context> 요소는 Tomcat 인스턴스에서 가장 일반적으로 사용되는 컨테이너입니다.

    각 <Context> 요소는 정의된 <Host> 내에서 실행되는 개별 웹 응용 프로그램을 나타냅니다.
    <Host> 내에서 정의할 수 <Context> 수에는 제한이 없습니다

    톰캣 인스턴스가 구동 되었다면 http://localhost:8080 에 접속한다.

    port를 변경하기 위해서는 CATALINA_HOME/conf/server.xml 파일에 다음 내용을 수정한다.

    <Connector port=”8080″ protocol=”HTTP/1.1″ connectionTimeout=”20000″ redirectPort=”8443″ />

    <Connector port=”80″ protocol=”HTTP/1.1″ connectionTimeout=”20000″ redirectPort=”8443″ />

    • Tomcat에 웹 어플리케이션 배치

    • The Tomcat Directory Structure
      • /bin
        • startup, shutdown 스크립트를 포함하고 있다. 또한 톰캣을 구동하기 위해 필요한 jars 파일도 포함한다.
      • /conf
        • 톰캣을 위한 configuration 파일들을 가지고 있다.(server.xml, web.xml)
      • /lib
        • jar 파일들을 가지고 있으며 모든 톰캣 컴포넌트가 공유한다
        • 톰캣에 배치되는 모든 웹 어플리케이션은 여기에 저장된 라이브러리를 액세스 할 수 있다.
        • Servlet API 또는 JSP API 라이브러리를 포함한다.
      • /logs
        • 톰캣 로그 파일이 저장된다.
      • /temp
        • 임시 파일이 저장된다.
      • /webapps
        • 모든 웹 어플리케이션이 저장되는 디렉토리 (war)
      • /work
    • Executing Tomat scripts
      • catalina.sh or catalina.bat
        • 톰캣을 구동 또는 종료하는 스크립트
        • catalina arguments
          • catalina start
            • 새로운 분리 프로세스로서 톰캣 서버를 구동한다.
          • catalina stop
            • 톰캣 서버 중단
          • catalina run
            • 현재 윈도우 또는 터미널에서 톰캣을 구동한다 .현재 세션 또는 터머널에서만 유지
          • catalina debug
          • catalina version
          • catalina configtest
            • 현재 톰캣 구성이 정상적인지 테스트
          • catalina jpda start
            • JPDA 디버깅 모드로 구동
    • Passing Runtime Options to Catalina Script
      • 자바 어플리케이션을 구동할 때 JVM에 다른 옵션을 필요할 경우 도 있다. 가령 메모리 셋팅, 인코딩, 호스트네임, 포트
      • export JAVA_OPTS=”-Dfile.encoding=utf-8″
        • 위 옵션은 같은 로컬 머신에 구동하는 톰캣 뿐만 아니라 모든 자바 프로세스에 영향을 미친다.
      • export CATALINA_OPTS=” -Xms256m -Xmx1g -XX:MaxPermSize=256m”
        • 오직 톰캣 프로세스에만 영향을 미친다.
    • Tomcat Configuration Files(/conf)
      • 톰캣의 메인 설정 파일은 server.xml파일이다.
        • 톰캣의 주요한 engeines, hosts, conetext 설정 정보가 저장되어 있다.
      • context.xml은 default context 설정 정보가 저장되어 있다.
        • 톰캣의 모든 context가 설정 정보를 공유한다.
      • 각 context는 자신만의 고유한 설정 정보를 가질수 있다. 가령,
        • CATALINA_HOME/conf/ENGINE_NAME/HOST_NAME/CONTEXT_NAME.xml
    • JAVA Web Applications
      • 톰캣의 가장 중요한 기능은 자바 웹 어플리케이션의 컨테이너 기능을 수행하는 것이다.
      • Web Applications의 정의
        • 웹 어플리케이션은 서블릿, html 페이지, 클래스 그리고 다른 리소스 자원들의 집합이다.
        • 웹 어플리케이션은 다음 오브젝트 리스트의 결합을 담을수 있는 컨테이너(그릇)이다.
          • Servlets
          • Java Server Pages(JSPs)
          • Utility Classes
          • Static documents, including HTML, images, JavaScript libraires, CSS, 기타등등
          • Client side classes
          • Meta-informatin describing the web application
        • 각 웹 어플리케이션은 오직 하나의 서블릿 컨텍스트를 가진다.
    • Directory Structure
      • 기본 어플리케이션 디렉토리 위치
        • CATALINA_HOME/webapps
        • /apps
          • 웹 어플리케이션의 루트 디렉토리. JSP 그리고 HTML 파일이 저장된다.
          • root 디렉토리이다.
        • /apps/WEB-INF
          • root 디렉토리에 포함되지 않은 어플리케이션 리소스를 포함하고 있다.
          • 클라이언트에 의해 직접 액세스 되는 파일은 여기에 저장하면 안된다.
        • /apps/WEB-INF/classes
          • servlet 그리고 유틸리티 classes 저장 위치
        • /apps/WEB-INF/lib
          • Java Archive Filse(jar) 파일 저장 위치
      • 자바 클래스 로더는 classes 디렉토리의 클래스를 먼저 로드한 다음 lib 디렉토리의 jar 파일을 로드 한다.
      • classes와 lib에 동일한 오브젝트가 존재할 때 classes 디렉토리 위치의 오브젝트가 우선 한다.
    • Deployment Descriptor(배치 기술자) – web.xml
      • web.xml 파일은 WEB-INF/ 디렉토리에 위치한다.
      • 웹 어프리케이션의 전체 설정 정보를 가지고 있다.
      • 배치 기술자는 다음 내용을 포함하고 있다.
        • Servlet 정의
        • Servlet 초기화 파라메터
        • Session 설정 파라메터
        • Servlet/JSP 매핑
        • MIME type 매핑
        • 보안 설정
        • Welcome file list
        • 에러 페이지 리스트
        • 리소스 그리고 환경 변수
      • sample
    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
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    <?xml version="1.0" encoding="UTF-8"?>
        id="admin" version="2.5">
     
        <display-name>admin</display-name>
     
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
     
        <!-- ~~~~~~~~ application name ~~~~~~~~ -->
        <context-param>
            <param-name>webAppRootKey</param-name>
            <param-value>admin</param-value>
        </context-param>
     
        <!-- ~~~~~~~~ spring context loader ~~~~~~~~ -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <listener>
            <listener-class>
                org.springframework.web.context.request.RequestContextListener
            </listener-class>
        </listener>
     
        <!-- ~~~~~~~~ spring web dispatcher ~~~~~~~~ -->
        <servlet>
            <servlet-name>webDispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    classpath*:/META-INF/spring/admin.mvc.xml
                </param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
     
        <servlet-mapping>
            <servlet-name>webDispatcher</servlet-name>
            <url-pattern>*.jsp</url-pattern>
        </servlet-mapping>
     
        <!-- ~~~~~~~~ error page setting ~~~~~~~~ -->
        <error-page>
            <error-code>400</error-code>
            <location>/WEB-INF/views/error/error_400.jsp</location>
        </error-page>
     
        <!-- ~~~~~~~~ UTF-8 encoding ~~~~~~~~ -->
        <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
     
    </web-app>
    • Tomcat에 웹 어플리케이션 수동 설치
      • 새로운 웹 어플리케이션을 만들 때 가장 먼저 해야하는 일은 디렉토리 구조를 만드는 것이다.
      • 디렉토리 구조
        • /apps
        • /apps/WEB-INF/
        • /apps/images/
        • /apps/scripts/
        • /apps/styles/
      • /apps/WEB-INF/ 디렉토리는 오직 서블릿 컨테이너만 접근 가능 하다.
    • 서블릿 추가
      • javac HelloWorld.java -cp CATALINA_HOME/lib/servelet-api.jar
    • War Archive 배치
      • war 파일은 표준 자바 웹 어플리케이션 패키징 메소드이다.
      • java cvf apps.war .
      • 마지막에 period(.)  은 현재 디렉토리를 참조한다.
      • war 파일을 배치하기 위해서 /CATALINA_HOME/webapps 디렉토리에 복사한다.
      • war 파일을 unpack 하지 않기 위해서는 &lt;Context&gt; 엘리먼트를 다음과 같이 지정한다.  하지만 performance를 위해서라면 unpack 하는 것이 좋다.
      • <Context path=”/apps” docBase=”apps” unpackWar=”false”> =>  CATALINA_HOME/conf/server.xml


    출처 - https://jonghwasu.wordpress.com/2013/02/01/apache-tomcat7/








    C:\Tomcat 5.0\conf에 server.xml를 열어봅시다.

    무쟈게 복잡하죵? ㅎㅎ

     

    일단 하나하나씩 알아 봅시다.

     

    server.xml는 다음과 같은 구조로 구성되어있습니다.

    -. Top level Elements : <server>는 설정파일 전체에서 Root Element이며 반면에

        <service>는 하나의 Engine과 연관된 Connector들의 집합을 말합니다.

        top level elements에는 <server>, <service>등이 있습니다.

     

    -. Connector : 외부 Client와 요청을 주고 응답을 받는 Interface를 말합니다.

        connector에는 <HTTP>, <AJP>등이 있습니다. 오호~ 프로토콜과 관계된 것들이군요

     

    -. Containers : 요청을 받아 응답을 처리하는 기능들의 Component를 말합니다.

         하나의 Engine은 하나의 Service에대한 모든 요청을 처리하며,

         하나의 Host는 하나의 Virtual Host에 대한 모든 요청을 처리하며,

         하나의 Context는 하나의 Web Appliction에 대한 모든 요청을 처리합니다.

        container에는 <Context>, <Engine>, <Host>등이 있습니다.

     

    -. Nested Component : Nested Component는  Container의 어느 Element안에 중첩될 수도

        있으며 어떤 Element들은 Container안에도 중첩될 수 있는 반면에 다른것들은

         Context안에만 중첩될 수 있다.

        <Logger>, <Realm>, <Resources>, <Loader>등이 있습니다.

     

    위에서 보니 볼것이 생각외로 많습니다.

    하지만 머니머니 해도 젤 중요한건 Context이겠죠. 요 Context만 살작 보겠습니다.

     

    Context가 그럼 멀까요?

    Context는 특별한 Viertual Host에서 작동하는 하나의 Web Application입니다.

    각 Web Application은 하나의 Web Application Archive(WAR) file나,

    이에 대응하는 unpacked된 Content를 가지는 directory를 말합니다.

     

    Tomcat 4.x 대 까지만 해도 context는 server.xml에 기술할 수 있었습니다.

    하지만 Tomcat 5.x대 부터는 달라졌더군요.

    <Host> elements안에 contenxt를 추가할 수 있지만 xml형식의 개별적인 파일로 저장 할 수도 있습니다.

    개별적으로 저장하려면 위치는 $CATALINA_HOME/conf/[enginename]/[hostname]/ directory 가 됩니다.

    실제로 이 위치에 가보면 admin.xml등의 파일이 있는 것을 볼 수 있습니다.

    디폴트로 된 context의 xml를 만들려면 ROOT.xml로 만드시면 됩니다.

    참고로 tomcat문서에서는 <Context>를 server.xml에 직접 기술하는것을 강력히 비추천 하는군요 -ㅠ-

     

    예제) ROOT.xml 입니다. (reloadable="true"를 추가했군요~)

    <Context path="" docBase="${catalina.home}/webapps/ROOT"
            debug="0" privileged="true" reloadable="true">

      <Logger className="org.apache.catalina.logger.FileLogger"
                     directory="logs"  prefix="localhost_log." suffix=".txt"
                timestamp="true"/>

    </Context>

    Logger를 잠시보면 로거로 FileLogger라는 클래스를 사용할 것이며

    디렉토리는 톰캣의 logs디렉토리를, 파일명은 localhost_log.yyyy-mm-dd.txt로 하겠다는 겁니다.

     

    여기에 test라는 Context를 하나 더 추가해 봅시다.

    우선 test.xml을 다음과 같이 만들어 봅시다.

    <Context path="/test" docBase="${catalina.home}/webapps/test"
            debug="0" privileged="true" reloadable="true">

      <Logger className="org.apache.catalina.logger.FileLogger"
                     directory="logs"  prefix="localhost_log." suffix=".txt"
                timestamp="true"/>

    </Context>

    path에는 context 경로를 적습니다. 각 요청 URI의 시작부분이 context 경로와 같을 때 해당 웹어플리케이션이 그 요청을 처리하게 됩니다. docBase는 이 웹어플리케이션에 대한 파일 경로입니다

    설정 끝~

    http://localhost:8080/test 를 요청하게 되면 해당 /webapps/test 밑에 있는 파일을 요청하게 됩니다

     

    그럼 Context의 속성을 알아봅시다.

     

    속성설명
    backgroundProcessorDelay이 값은 컨텍스트와 그 자식 컨테이너에서 background process method가 invoke되는 delay 시간을 나타낸다.
    이 값을 양수로 설정하면 어떤 쓰레드가 분기되어 일정 시간 후에 이 쓰레드가 해당 host와 자식 컨테이너에서 background process method를 실행시킵니다
    만약 설정하지 않으면 디폴트값인 -1을 가지며 음수의 값은 부모 host의 background processing 정책을 사용한다는 것입니다.
    참고로 컨텍스트는 세션을 종료하거나 클래스 리로딩을 위한 모니터링등을 위해 background processing을 사용합니다.
    className

    사용할 Java 구현체 클래스의 이름. 이 클래스는 반드시 org.apache.catalina.Context 인터페이스를 구현해야 합니다. 지정하지 않으면 표준값 (아래에 정의됩니다)이 사용됩니다

    cookies

    true(디폴트)로 지정하면 클라이언트가 쿠키를 지원하는 경우 세션확인의 통신수단(session identifier communication)으로 쿠키를 사용합니다. false로 지정하면 세션확인의 통신수단으로 쿠키 사용을 하지 않고, 어플리케이션에 의한 URL 다시쓰기(URL rewriting)에만 의존한다는 의미입니다.

    crossContext

    true로 지정하면 이 어플리케이션에서 ServletContext.getContext() 호출을 통해, 이 가상호스트에서 실행중인 다른 웹어플리케이션에 대한 요청디스패쳐(request dispatcher)를 성공적으로 얻을 수 있습니다. 보안상의 이유로 false(디폴트)로 지정하면 getContext()는 언제나 null을 반환하게 됩니다.

    docBase

    이 웹어플리케이션에 대한 Document Base (Context Root로도 알려져 있습니다) 디렉토리, 또는 웹어플리케이션 아카이브 파일의 경로명(웹어플리케이션을 WAR 파일로 직접 실행하는 경우)을 나타냅니다. 이 디렉토리나 WAR 파일에에 대한 절대경로명을 지정할 수도 있고, 이 Context가 정의된 Host의 appBase 디렉토리에 대한 상대경로명을 지정할 수도 있습니다

    overridetrue로 설정하면 DefaultContext element를 관련된 host에서 명백하게 상속받아 사용합니다
    기본값으로 Defaultcontext element가 사용됩니다
    privileged

    true로 설정하면 이 컨텍스트는 관리자서블릿(manager servlet) 같은 컨테이너 서블릿을 사용할 수 있습니다.

    path

    이 웹어플리케이션의 컨텍스트 경로(context path)를 나타내며, 각 요청 URI의 시작부분이 컨텍스트 경로와 같을 때 해당 웹어플리케이션이 그 요청을 처리하게 됩니다. 하나의 특정 Host 내의 컨텍스트 경로들은 모두 각각 유일해야 합니다. 만약 컨텍스트 경로를 빈 스트링("")으로 지정하면, 이 Context는 이 Host에 대한 디폴트 웹어플리케이션으로 정의된 것입니다. 디폴트 웹어플리케이션은 다른 Context 들에 해당되지 않는 모든 요청을 처리할 것입니다.

    reloadable

    true로 지정하면, Catalina는 /WEB-INF/classes/와 /WEB-INF/lib 안 클래스 들의 변경여부를 감시하다가, 변경이 발견되면 웹어플리케이션을 자동으로 재적재(reload)합니다. 이 기능은 개발중에는 매우 유용하지만 얼마간의 실행부하(runtime overhead)가 발생하므로, 실제 운영할 용도로 어플리케이션을 배치(deploy)할 때는 사용하지 않도록 합니다. 그러나 이미 배치가 끝난 어플리케이션이라도 Manager 웹어플리케이션을 이용하면 필요할 때 재적재 하도록 할 수 있습니다

    wrapperClass

    이 Context로 관리할 서블릿 들에 대해 사용할 org.apache.catalina.Wrapper 구현체 클래스의 Java 클래스명입니다. 지정하지 않으면 표준값이 사용됩니다

     

    from http://jakarta.apache.org

     

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

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

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

    저자 : GoodBug (unicorn@jakartaproject.com)

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

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


    출처 -  http://www.jakartaproject.com/board-read.do?boardId=jakarta&boardNo=1102844820026&command=READ&t=1328133167517 









    ▣ server.xml 파일이란?

    1. 말그대로.. server에 대한 설정 파일이다.

     

    ▣ 디렉토리 위치?

    :%CATALINA_HOME%\conf\server.xml         //CATALINA_HOME은 톰캣의 홈디렉토리!~

     

    ▣ 구조

    톰캣을 설치한 후, 가장 기본적 형태!~ parent-children 관계이다..

     

    Server는 전체 JVM을 대표하는 단 하나의 요소이다.
    Server는 한개 이상의 Service 객체를 가지고 지정된 포트로 shutdown 커맨드를 listen한다.

    Server는 그 자체가 Container가 아니므로 'Valves'나 'Loggers'같은 것은 정의할 수 없다.

    <Server port="8005" shutdown="SHUTDOWN">

        필요한 리스너 등록!~

        <Listener className="org.apache.catalina.core.AprLifecycleListener" />

        Global JNDI resources!~
        <GlobalNamingResources>
            <Environment name="simpleVal!ue" ... />
            <Resource name="UserDatabase" ... />
        </GlobalNamingResources>

        Service는 하나의 Container를 공유하는 한개 이상의 Connectors의 모임이다.
        일반적으로.. 위에서 호칭한 Container를 'Engine'이라 한다.
        Service태그에서 톰캣의 독립 서비스를 정의하자

        <Service name="Catalina">

            Connector는 요청을 받고 응답을 리턴하는 endpoint이다.
            각 Connector는 요청을 처리하기 위해 연관된 Container에게 요청을 넘긴다.

            <Connector port="8080" ... />
            <Connector port="8009" ... />

            Engine은 적절한 Host(virtual host)로 처리를 넘기는 entry point이다.
            <Engine name="Catalina" defaultHost="localhost">
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm" .../>

                default virtual Host 정의
                <Host name="localhost" appBase="webapps">
                </Host>
            </Engine>
        </Service>
    </Server>

     

     

    ▣ 기타 설명


    1. HTTP 포트를 80으로 바꾸면 http://localhost:8080을 안 써도 된다.

    즉 http://localhost 만 쓰면 된다는 말!~

    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector port="8080" maxHttpHeaderSize="8192"              // 8080 -> 80
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />

     

    2. Context ?

    : Context는 특별한 Viertual Host에서 작동하는 하나의 Web Application 이다..

     

    3. Web Application을 추가 하기 위해서(deploy)

    Application Context를 추가해야 하는데..

    위에서 설명한 <Host></Host> 사이에 <Context>를 추가하는 것이 예전 방법 이었다.(Tomcat 4.x 이하)

     

    그러나!!

     

    자카르타에서는 더이상 server.xml 내에 Context를 추가하는 것을 권장하지 않는다..

    (그것도 강력히 비추한다 -ㅇ-..)

    그러면 방법은??

     

    다음 글에 써 놓았다.... - -..

    톰캣에 어플리케이션 추가하기! 

    ▣ 톰캣(tomcat)에 어플리케이션을 추가하는 방법은 두가지가 있다.

    하나씩 알아보도록 하자.

     

    1. webapps 디렉토리 밑에 넣는 방법

    장점 : 웹 어플리케이션의 폴더구조만 가지고 있다면 자동으로 웹어플리케이션이 설정된다.

    단점 : 지정된 디렉토리(톰캣\webapps\'어플리케이션명')의 하위 이외에는 설정이 불가하다.

    방법 :

      기본 설치된 톰캣 디렉토리에서 '톰캣\webapps\어플리케이션명' 이렇게 넣어주기만 하면..

      바로.. http://localhost/어플리케이션명 ........ 으로 접근 가능하다.

     

    참고1) 웹 어플리케이션의 폴더구조

    어플리케이션명\WEB-INF                 ----------> 이 디렉토리 필수!

    어플리케이션명\WEB-INF\web.xml  ----------> 이 파일 필수!

     

    참고2) web.xml의 최소내용

    <?xml version="1.0" encoding="euc-kr"?>

    <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
        version="2.4">
    </web-app>


    참고3) index.html이 있어야 되겠죠?

      web.xml에 설정한 welcome파일이 있어야 해당 context가 정상적으로 호출이 된답니다

      ----> web.xml중 <welcome-file-list>태그에 적은 거 기억나시죠?


    참고4) 어플 추가후 톰캣서버리부팅없이 바로 접근가능하답니다 ㅎㅎ

     

    2. 임의의 디렉토리에 웹어플리케이션을 위치시키고 싶을 때.

    장점 : '톰캣\webapps\' 디렉토리에 구속될 필요가 없다.

    방법 :

    이전에 설명한.. server.xml에서 설정하는 방법도 있으나 이것은 자카르타에서 비추하는 방법이기 때문에

    설명은 생략토록 한다.

     

    앞으로는 xml형식의 파일로 Application Context를 저장하라고 하고 있다.

    아래처럼!~

     

    %CATALINA_HOME%\conf\Catalina\localhost\컨텍스트명.xml

     

    기존에 존재하는 host-manager.xml, manager.xml 등의 파일을 저장해서 이름을 바꾸고

    안에 내용중 docBase와 path만 바꾸면 끝!~

    설정이 훨씬 쉽게 되었다!!! ㅎㅎ

     

    - path : 웹어플리케이션의 경로명(http://localhost/'요기 붙을 내용')

    - docBase : 웹어플리케이션이 위치한 폴더의 경로명(실제 경로)

     

    <Context path="/myTest" docBase="C:\myTest"
                  debug="0" privileged="true" reloadable="true">
        <Logger className="org.apache.catalina.logger.FileLogger"
                     directory="logs"  prefix="localhost_log." suffix=".txt"
                     timestamp="true"/>
    </Context>

     

     

    ※ROOT로 만들고 싶다면 ROOT.xml로 만들면 됨.

    ※server.xml의 HOST 항목중 appbase 속성값과 위의 docBase가 동일하면 톰캣 콘솔에..

    에러가 발생하므로 경로를 다르게 해주자!~

     


    ▣ Context 속성(참조 : http://www.jakartaproject.com/article/jakarta/110284482002600 )

     속성

    설명

     backgroundProcessorDelay  이 값은 컨텍스트와 그 자식 컨테이너에서 background process method가 invoke되는 delay 시간을 나타낸다.
    이 값을 양수로 설정하면 어떤 쓰레드가 분기되어 일정 시간 후에 이 쓰레드가 해당 host와 자식 컨테이너에서 background process method를 실행시킵니다
    만약 설정하지 않으면 디폴트값인 -1을 가지며 음수의 값은 부모 host의 background processing 정책을 사용한다는 것입니다.
    참고로 컨텍스트는 세션을 종료하거나 클래스 리로딩을 위한 모니터링등을 위해 background processing을 사용합니다.
     className 

    사용할 Java 구현체 클래스의 이름. 이 클래스는 반드시 org.apache.catalina.Context 인터페이스를 구현해야 합니다. 지정하지 않으면 표준값 (아래에 정의됩니다)이 사용됩니다

     cookies 

    true(디 폴트)로 지정하면 클라이언트가 쿠키를 지원하는 경우 세션확인의 통신수단(session identifier communication)으로 쿠키를 사용합니다. false로 지정하면 세션확인의 통신수단으로 쿠키 사용을 하지 않고, 어플리케이션에 의한 URL 다시쓰기(URL rewriting)에만 의존한다는 의미입니다.

     crossContext 

    true 로 지정하면 이 어플리케이션에서 ServletContext.getContext() 호출을 통해, 이 가상호스트에서 실행중인 다른 웹어플리케이션에 대한 요청디스패쳐(request dispatcher)를 성공적으로 얻을 수 있습니다. 보안상의 이유로 false(디폴트)로 지정하면 getContext()는 언제나 null을 반환하게 됩니다.

     docBase 

    이 웹어플리케이션에 대한 Document Base (Context Root로도 알려져 있습니다) 디렉토리, 또는 웹어플리케이션 아카이브 파일의 경로명(웹어플리케이션을 WAR 파일로 직접 실행하는 경우)을 나타냅니다. 이 디렉토리나 WAR 파일에에 대한 절대경로명을 지정할 수도 있고, 이 Context가 정의된 Host의 appBase 디렉토리에 대한 상대경로명을 지정할 수도 있습니다

     override true로 설정하면 DefaultContext element를 관련된 host에서 명백하게 상속받아 사용합니다
    기본값으로 Defaultcontext element가 사용됩니다
     privileged 

    true로 설정하면 이 컨텍스트는 관리자서블릿(manager servlet) 같은 컨테이너 서블릿을 사용할 수 있습니다.

     path 

    이 웹어플리케이션의 컨텍스트 경로(context path)를 나타내며, 각 요청 URI의 시작부분이 컨텍스트 경로와 같을 때 해당 웹어플리케이션이 그 요청을 처리하게 됩니다. 하나의 특정 Host 내의 컨텍스트 경로들은 모두 각각 유일해야 합니다. 만약 컨텍스트 경로를 빈 스트링("")으로 지정하면, 이 Context는 이 Host에 대한 디폴트 웹어플리케이션으로 정의된 것입니다. 디폴트 웹어플리케이션은 다른 Context 들에 해당되지 않는 모든 요청을 처리할 것입니다.

     reloadable 

    true 로 지정하면, Catalina는 /WEB-INF/classes/와 /WEB-INF/lib 안 클래스 들의 변경여부를 감시하다가, 변경이 발견되면 웹어플리케이션을 자동으로 재적재(reload)합니다. 이 기능은 개발중에는 매우 유용하지만 얼마간의 실행부하(runtime overhead)가 발생하므로, 실제 운영할 용도로 어플리케이션을 배치(deploy)할 때는 사용하지 않도록 합니다. 그러나 이미 배치가 끝난 어플리케이션이라도 Manager 웹어플리케이션을 이용하면 필요할 때 재적재 하도록 할 수 있습니다

     wrapperClass 

    이 Context로 관리할 서블릿 들에 대해 사용할 org.apache.catalina.Wrapper 구현체 클래스의 Java 클래스명입니다. 지정하지 않으면 표준값이 사용됩니다


     

    출처 

    http://blog.daum.net/_blog/BlogTypeView.do?blogid=090sk&articleno=5494233&_bloghome_menu=recenttext#ajax_history_home

     



     





    Apache Tomcat 7

    More about the Cat

    This article is meant for advanced programmers who is interested to know more about Tomcat; or using Tomcat for production. For novices, read "How to Install and Get Started with Tomcat".

    The authoritative source of information on Tomcat is the Tomcat's documentation, available under Tomcat's "webapps\docs" directory. You may also refer to the Java Servlet, JSP and JSF specifications, as Tomcat is the Reference Implementation for these technologies.

    I shall assume that Tomcat is installed in d:\myproject\tomcat, and shall denote this directory as <TOMCAT_HOME> or <CATALINA_HOME> - "Catalina" is the codename for Tomcat 5 and above.

    1.  Tomcat Architecture and Configuration

    1.1  Tomcat's Installed Directory Structure

    Tomcat installation provides these directories:

    • bin: for Tomcat's binaries and startup scripts.
    • conf: global configuration applicable to all the webapps. The default installation provides:
      • One Policy File: catalina.policy for specifying security policy.
      • Two Properties Files: catalina.properties and logging.properties,
      • Four Configuration XML Files: server.xml (Tomcat main configuration file), web.xml (global web application deployment descriptors), context.xml (global Tomcat-specific configuration options) and tomcat-users.xml (a database of user, password and role for authentication and access control).
      The conf also contain a sub-directory for each engine, e.g., Catalina, which in turn contains a sub-sub-directory for each of its hosts, e.g., localhost. You can place the host-specific context information (similar to context.xml, but named as webapp.xml for each webapp under the host).
    • lib: Keeps the JAR-file that are available to all webapps. The default installation include servlet-api.jar (Servlet), jasper.jar (JSP) and jasper-el.jar (EL). You may also keep the JAR files of external package here, such as MySQL JDBC driver (mysql-connector-java-5.1.{xx}-bin.jar) and JSTL (jstl.jar and standard.jar).
    • logs: contains the engine logfile Catalina.{yyyy-mm-dd}.log, host logfile localhost.{yyyy-mm-dd}.log, and other application logfiles such as manger and host-manager. The access log (created by the AccessLogValve) is also kept here.
    • webapps: the default appBase - web applications base directory of the host localhost.
    • work: contains the translated servlet source files and classes of JSP/JSF. Organized in hierarchy of engine name (Catalina), host name (localhost), webapp name, followed by the Java classes package structure.
    • temp: temporary files.

    1.2  Tomcat Architecture

    Tomcat is an HTTP server. Tomcat is also a servlet container that can execute Java Servlet, and converting JavaServer Pages (JSP) and JavaServerFaces (JSF) to Java Servlet. Tomcat employs a hierarchical and modular architecture as illustrated:



    1.3  Main Configuration File "server.xml"

    Tomcat's main configuration file is the "server.xml", kept under the <CATALINA_HOME>\conf directory. The default "server.xml" is reproduced as follows (after removing the comments and minor touch-ups):

    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
    32
    33
    34
    35
    36
    37
    38
    <?xml version='1.0' encoding='utf-8'?>
    <Server port="8005" shutdown="SHUTDOWN">
      <Listener className="org.apache.catalina.core.JasperListener" />
      <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
      <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
      <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
     
      <GlobalNamingResources>
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
                  description="User database that can be updated and saved"
                  factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                  pathname="conf/tomcat-users.xml" />
      </GlobalNamingResources>
     
      <Service name="Catalina">
        <Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />
        <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
     
        <Engine name="Catalina" defaultHost="localhost">
     
          <Realm className="org.apache.catalina.realm.LockOutRealm">
            <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase"/>
          </Realm>
     
          <Host name="localhost"  appBase="webapps"
                unpackWARs="true" autoDeploy="true">
            <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                   prefix="localhost_access_log." suffix=".txt"
                   pattern="%h %l %u %t &quot;%r&quot; %s %b" />
          </Host>
        </Engine>
      </Service>
    </Server>
    Server

    Server (Line 2) is top component, representing an instance of Tomcat.It can contains one or more Services, each with its own Engines and Connectors.

    <Server port="8005" shutdown="SHUTDOWN"> ...... </Server>
    Listeners

    The Server contains several Listeners (Lines 3-7). A Listener listens and responses to specific events.

    • The JasperListener enables the Jasper JSP engine, and is responsible for re-compiling the JSP pages that have been updated.
      <Listener className="org.apache.catalina.core.JasperListener" />
    • The GlobalResourcesLifecycleListener enables the global resources, and makes possible the use of JNDI for accessing resources such as databases.
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
    Global Naming Resources

    The <GlobalNamingResources> element (Line 9-15) defines the JNDI (Java Naming and Directory Interface) resources, that allows Java software clients to discover and look up data and objects via a name.

    The default configuration defines a JNDI name called UserDatabase via the <Resource> element (Line 10-14), which is a memory-based database for user authentication loaded from "conf/tomcat-users.xml".

    <GlobalNamingResources>
      <Resource name="UserDatabase" auth="Container"
                type="org.apache.catalina.UserDatabase"
                description="User database that can be updated and saved"
                factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                pathname="conf/tomcat-users.xml" />
    </GlobalNamingResources>

    You can define other global resource JNDI such as MySQL database to implement connection pooling.

    Services

    Service associates one or more Connectors to a Engine. The default configuration defines a Service called "Catalina", and associates two Connectors: HTTP and AJP to the Engine.

    <Service name="Catalina"> ...... </Service>
    Connectors

    Connector is associated with a TCP port to handle communications between the Service and the clients. The default configuration defines two Connectors:

    • HTTP/1.1: Handle HTTP communication and enable Tomcat to be an HTTP server. Clients can issue HTTP requests to the server via this Connector, and receive the HTTP response messages.
      <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
      The default chooses TCP port 8080 to run the Tomcat HTTP server, which is different from the default port number of 80 for HTTP production server. You can choose any number between 1024 to 65535, which is not used by any application, to run your Tomcat server.
      The connectionTimeout attribute define the number of milliseconds this connector will wait, after accepting a connection, for the request URI line (request message) to be presented. The default is 20 seconds.
      The redirect attribute re-directs the SSL requests to TCP port 8443.
    • AJP/1.3: Apache JServ Protocol connector to handle communication between Tomcat server and Apache HTTP server.
      <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
      You could run Tomcat and Apache HTTP servers together, and let the Apache HTTP server handles static requests and PHP; while Tomcat server handles the Java Servlet/JSP. Read "How To Configure Tomcat to work with Apache".
    Containers

    Tomcat refers to EngineHostContext, and Cluster, as container. The highest-level is Engine; while the lowest-level is Context. Certain components, such as Realm and Valve, can be placed in a container.

    Engine

    Engine is the highest-level of a container. It can contains one or more Hosts. You could configure a Tomcat server to run on several hostnames, known as virtual host.

    <Engine name="Catalina" defaultHost="localhost">

    The Catalina Engine receives HTTP requests from the HTTP connector, and direct them to the correct host based on the hostname/IP address in the request header.

    Realm

    Realm is a database of user, password, and role for authentication (i.e., access control). You can define Realm for any container, such as EngineHost, and Context, and Cluster.

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

    The default configuration defines a Realm (UserDatabaseRealm) for the Catalina Engine, to perform user authentication for accessing this engine. It uses the JNDI name UserDatabase defined in the GlobalNamingResources.

    Besides the UserDatabaseRealm, there are: JDBCRealm (for authenticating users to connect to a relational database via the JDBC driver); DataSourceRealm (to connect to a DataSource via JNDI; JNDIRealm (to connect to an LDAP directory); and MemoryRealm (to load an XML file in memory).

    Hosts

    Host defines a virtual host under the Engine, which can in turn support many Contexts (webapps).

    <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">

    The default configuration define one host called localhost. The appBase attribute defines the base directory of all the webapps, in this case, <CATALINA_HOME>\webapps. By default, each webapp's URL is the same as its directory name. For example, the default Tomcat installation provides four webapps: docsexampleshost-manager and manager under the webapps directory. The only exception is ROOT, which is identified by an empty string. That is, its URL is http://localhost:8080/.

    The unpackWARs specifies whether WAR-file dropped into the webapps directory shall be unzipped. For unpackWARs="false", Tomcat will run the application from the WAR-file directly, without unpacking, which could mean slower execution.

    The autoDeploy attribute specifies whether to deploy application dropped into the webapps directory automatically.

    Cluster

    Tomcat supports server clustering. It can replicate sessions and context attributes across the clustered server. It can also deploy a WAR-file on all the cluster.

    Valve

    Valve can intercept HTTP requests before forwarding them to the applications, for pre-processing the requests. A Valve can be defined for any container, such as EngineHost, and Context, and Cluster.

    In the default configuration, the AccessLogValve intercepts an HTTP request and creates a log entry in the log file, as follows:

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b" />

    Other valves include:

    • RemoteAddrValve: which blocks requests from certain IP addresses,
    • RemoteHostValve: which blocks request based on hostnames,
    • RequestDumperValve: which logs details of the requests,
    • SingleSignOn Valve: when placed under a <host>, allows single sign-on to access all the webapp under the host.

    1.4  Other Configuration Files: web.xmlcontext.xmltomcat-users.xml

    [TODO]

    They are so many things that you can configured in Tomcat. I describe some of the configurations that I found useful in this section.

    Enabling Directory Listing

    When the request URL refers to a directory instead of a file, e.g., http://host:port/hello/, you can configure Tomcat to serve the directory listing, or a welcome file, or issue error "404 Page Not Found". Enabling directory listing is handy for test server but NOT desire for production server (as it reveal the directory structure and expose the entire directory hierarchy).

    Enabling Directory Listing for ALL Webapps

    To enable directory listing for all the web applications, you could modify the <CATALINA_HOME>\conf\web.xml, by changing "listings" from "false" to "true" for the "default" servlet, as follows:

    <!-- The default servlet for all web applications, that serves static     -->
    <!-- resources.  It processes all requests that are not mapped to other   -->
    <!-- servlets with servlet mappings.                                      -->
    <servlet>
      <servlet-name>default</servlet-name>
      <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
      <init-param>
        <param-name>debug</param-name>
        <param-value>0</param-value>
      </init-param>
      <init-param>
        <param-name>listings</param-name>
        <param-value>true</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
        
    <!-- The mapping for the default servlet -->
    <servlet-mapping>
      <servlet-name>default</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>
       
    <!-- ==================== Default Welcome File List ===================== -->
    <!-- When a request URI refers to a directory, the default servlet looks  -->
    <!-- for a "welcome file" within that directory and, if present,          -->
    <!-- to the corresponding resource URI for display.  If no welcome file   -->
    <!-- is present, the default servlet either serves a directory listing,   -->
    <!-- or returns a 404 status, depending on how it is configured.          -->
    <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    

    The above configuration maps URL "\" (root directory of the web context) (in <url-pattern>) to Java class DefaultServlet (in <servlet-class>) via the common servlet name of default (in <servlet-name>). We enable directory listing by changing the servlet's initialization parameter listings to true.

    If a user requests for a directory, and the directory listing is enabled and it contains one of the files in the <welcome-file> list, the welcome file will be served; otherwise, the directory listing will be served. On the other hand, if a directory request is received and the directory listing is not enabled, the server returns an error "404 Page Not Found".

    Enabling Directory Listing for a particular Webapp

    If you wish to allow directory listing of a particular web application only, you could disable the directory listing in "<CATALINA_HOME>\conf\web.xml" globally, and define the following <servlet> and <servlet-mapping> in your application-specific WEB-INF\web.xml, as follows. You need to use another <servlet-name> in place of DefaultServlet.

    <servlet>
      <servlet-name>DirectoryListing</servlet-name>
      <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
      <init-param>
        <param-name>debug</param-name>
        <param-value>0</param-value>
      </init-param>
      <init-param>
        <param-name>listings</param-name>
        <param-value>true</param-value>
      </init-param>
    </servlet>
       
    <servlet-mapping>
      <servlet-name>DirectoryListing</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>
    Automatic Servlet Reload

    To enable automatic servlet reload (whenever a servlet is re-compiled), you need to specify <Context reloadable="true">...</Context>, in "<CATALINA_HOME>\conf\context.xml" for all web applications, or the <Context> element in "<CATALINA_HOME>\conf\server.xml" for a particular web application.

    The following messages appear on the Tomcat's console if you re-compile a servlet:

    XXX X, XXXX XX:XX:XX XX org.apache.catalina.core.StandardContext reload
    INFO: Reloading Context with path [/hello] has started
    XXX X, XXXX XX:XX:XX XX org.apache.catalina.core.StandardContext reload
    INFO: Reloading Context with path [/hello] is completed

    Enabling automatic servlet reload is handy during application development, but it requires significant runtime overhead to listen to the changes, and is not recommended for production systems. Instead, you could use the "manager" to trigger reloads on demand.

    Setting the Context Root Directory and Request URL of a Webapp

    A server could run many web applications. A webapp is also called a web context. The context root (or document base directory) refers to the base directory of a webapp. They are a few ways to configure a context root and its request URL of a webapp:

    1. (RECOMMENDED) Create a directory under <CATALINA_HOME>\webapps for your webapp. A context will be created with request URL set to the name of the directory. For example, if you create a directory called "hello" under Tomcat's "webapps". This application can be accessed by web users via URL http://host:port/hello.
      To change the request URL of the webapp, create a "context.xml" configuration file, as follows, and place it under "ContextRoot\META-INF":
      <Context path="/yourURLPath" />
    2. Alternatively, you can write a <Context> element in <CATALINA_HOME>\conf\server.xml, under the <Host> element. You can specify both the URL and the base directory. For example,
              ......
              ......
              <Context path="/ws" docBase="d:/workshop" reloadable="true">
              </Context>
            </Host>
          </Engine>
        </Service>
      </Server>
      In the above example, we define a web context with URL "/ws", with context root (docBase or document base directory) at "d:\workshop". This application can be accessed via URL http://host:port/ws.
      Take note that:
      • The configuration creates a mapping from the "URL Path" issued by the web users to the "document base directory" in the server's file system, where you store your webapp resources.
      • Place the <Context> element before the ending tag of the <Host> element.
      • Use Unix-style forward slash '/' as the directory separator in the configuration file, instead of Window-style back slash '\'.
      • The attribute reloadable="true" asks Tomcat to monitor your servlets for changes, and automatically reload the servlets if changes is detected. This is handy for a development system, but inefficient in a production system.
    3. Write a configuration file with a <Context> element and place it under Tomcat's "conf\Catalina\localhost". For example, suppose we wish to create a webapp with URL "hello" in base directory "d:\myproject\myHello", create the following file "hello.xml":
      <?xml version="1.0" encoding="UTF-8"?>
      <Context docBase="D:\myproject\myHello" path="/hello" />
    Changing the Default "webapps" Directory

    The default directory for deploying web applications is <CATALINA_HOME>\webapps. You could change the default by modifying the configuration file "conf\server.xml" <Host> element's "appBase" attribute as follows:

    <Host name="localhost" appBase="webapps"
          unpackWARs="true" autoDeploy="true"
          xmlValidation="false" xmlNamespaceAware="false">
       ......
    </host>

    2.  Deploying Webapps

    web context is a single web application (webapp). It is the lowest-level container, that you can define components such as Realm and Valve. By default, all webapps are kept under the <CATALINA_HOME>\webapps directory (as configured in the <host> element appBaseattribute.

    A Java webapp may contain many types of files, such as HTML, CSS, Scripts, images, JSP, servlet, utility classes, external library jar-files. A Java webapp must follow a strict directory structure as depicted in the Servlet/JSP specifications. This enables deployment in a Java-capable web server (such as Apache Tomcat and Glassfish). The resources must be kept in the correct directories and sub-directories.

    The URL of a webapp, by default, is the same as the base directory name (or context root) of the webapp.

    2.1  Webapp's Directory Structure



    The directory structure of a webapp is as follows:

    • "ContextRoot": contains the resources that are visible and accessible by the web clients, such as HTML, CSS, Scripts and images. These resources will be delivered to the clients as it is. You could create sub-directories such asimagescss and scripts, to further categories the various resources.
    • "ContextRoot\WEB-INF": This directory, although under the context root, is NOT visible to the web users. In other words, it is NOT accessible by the clients directly (for security reason). This is where you keep your application-specific configuration files such as "web.xml". It's sub-directories contain program classes, source files, and libraries.
    • "ContextRoot\WEB-INF\src": Keeps the Java program source files. It is optional but a good practice to separate the source files and classes to facilitate deployment.
    • "ContextRoot\WEB-INF\classes": Keeps the Java classes (compiled from the source codes). Classes defined in packages must be kept according to the Java package directory structure.
    • "ContextRoot\WEB-INF\lib": Keeps the libraries (jar-files), which are provided by other packages, specific and available to this webapp only.
    • "ContextRoot\META-INF\": This is also a hidden directory, to keep resources and configurations (e.g., "context.xml") related to the server. In contrast, "WEB-INF" is for resources related to this web application, independent of the server.

    2.2  Webapp-Specific Configuration Files

    These are the configuration files specific to a webapp: (a) WEB-INF\web.xml; (b) META-INF\context.xml.

    You can configure a webapp in many ways: (a) Write a <context> element in server.xml under <Host> element, (b) contextRoot\META-INF\context.xml, and (c) conf\Catalina\localhost\webapp.xml, and (d)conf\context.xml. See "Setting the Context Root Directory and Request URL of a Webapp".

    2.3  Web Application Deployment Descriptors - "web.xml"

    The "web.xml" contains the deployment descriptors. There are two sets of web.xml:

    1. <CATALINA_HOME>\conf\web.xml: applicable to ALL webapps.
    2. ContextRoot\WEB-INF\web.xml: applicable to the specific web context. It overrides the global setting, if any.

    The complete specification for "web.xml" can be found in the "Java Servlet Specification" under "Deployment Descriptor".

    A sample configuration of a servlet with most of its sub-elements is as follows:

    <web-app ......>
      ......
      <servlet>
        <icon>
          <small-icon>/images/icon.jpg</small-icon>
        </icon>
        <servlet-name>MyServlat</servlet-name>
        <display-name>My Servlet Display Name</display-name>
        <description>My Testing Servlet long description</description>
        <servlet-class>MyServletClassname</servlet-class>
        <init-param>
          <param-name>myParmName</param-name>
          <param-value>myParmValue</param-value>
        </init-param>
        <load-on-startup>25</load-on-startup>
      </servlet>
      ......
     
      <servlet-mapping>
        <servlet-name>MyServlat</servlet-name>
        <url-pattern>/sayhello</url-pattern>
      </servlet-mapping>
      ......
    </web-app>

    2.4  Deploying a Web Application in a WAR file

    You could use the JDK's jar utility to "zip" up all the files of a web application to produce a so-called WAR (Web Application Archive) file for deployment, or distribution.

    .... Change current directory to the web application's context root
    contextRoot> jar cvf test.war .

    Drop the test.war into <CATALINA_HOME>\webapps. A context called test will be created automatically. You can access the web application via URL http://host:port/test.

    Tomcat actually unpacks the test.war into a "test" directory in <CATALINA_HOME>\webapps. You need to remove this directory, if you reload a new version.

    3.  Running Tomcat

    3.1  Tomcat's Manager

    References:

    1. "Tomcat Web Application Manager How To" @ "webapps/docs/html-manager-howto.html".
    2. "Tomcat Manager App How-To" @ "webapps/docs/manager-howto.html".

    Tomcat "manager" webapp allows you to deploy a new web application; start, stop, reload or un-deploy an existing one, without having to shut down and restart the server, in a production environment.

    To enable Tomcat's manager, edit "<CATALINA_HOME>\conf\tomcat-users.xml" to include a role called "manager-gui" and a user with this role. You may also assign other roles, such as admin-gui for accessing the Tomcat "Host Manager".

    <role rolename="manager-gui" />
    <role rolename="manager-status" />
    <role rolename="manager-script" />
    <role rolename="manager-jmx" />
    
    <role rolename="admin-gui" />
    <role rolename="admin-script" />
     
    <user username="mymanager" password="xxxx" roles="manager-gui, admin-gui"/>

    To invoke manager web application, use http://localhost:8080/manager/html. You can use Tomcat's manager to:

    1. List all webapps.
    2. Start/Stop/Reload a particular webapp.
    3. Deploy a new webapp remotely, and undeploy a webapp without restarting the container.
    4. Terminate (or Invalidate) sessions - a session has a pre-set expiry time (e.g., 30 sec).
    5. Analyze memory leaks.
    6. View JVM status and Server status.

    Tomcat 7 provides separate manager roles for the GUI (manager-gui), status (manager-status), scripting (manager-script) and JMX proxy (manager-jmx), defined in "webapps/manager/WEB-INF/web.xml". This allows for fine-grained access control to management tasks.

    • manager-gui - Access to the HTML "web" interface, via:
      http://{host}:{port}/manager/html
    • manager-status - Access to the "Server Status" page only, via:
      http://{host}:{port}/manager/status
    • manager-script - Access to the "plain-text" interface, and to the "Server Status" page, via command in the form of:
      http://{host}:{port}/manager/text/{command}?{parameters}
       
      // Examples
      http://{host}:{port}/manager/text/list                  // List all webapps
      http://{host}:{port}/manager/text/deploy?path=/testapp  // Deploy webapp
    • manager-jmx - Access to JMX proxy interface and to the "Server Status" page, via:
      http://{host}:{port}/manager/jmxproxy/?{command}={parameter}

    For security reason, a user should NOT be given more than one of the following roles: manager-guimanager-script, and manager-jmx.

    Tomcat's "Administration Tool"

    The Tomcat "Adminstrative Tool" (or "Administrator Console") has been removed since Tomcat 6. Use JMX manager instead.

    3.2  Automatic Startup at Boot-time

    (Windows) Running Tomcat as a Windows Service

    You need to download the Windows-specific version of Tomcat (from Tomcat's download, choose 32-bit or 64-bit Windows' zip version, e.g., apache-tomcat-7.0.{xx}-windows-x86.zip).

    Read "Windows service How-To" in the Tomcat documentation (<CATALINA_HOME>\webapps\docs\windows-service-howto.html).

    In a production environment, it is more convenient to run Tomcat as a service, so that it can start automatically whenever the system is started (or re-start automatically after an unexpected interruption).

    To install Tomcat as a service, start a CMD shell (with administrator right) and run the <CATALINA_HOME>\bin\service.bat with install option:

    ... Change directory to <CATALINA_HOME>\bin ...
    <CATALINA_HOME>\bin> service install
    Installing the service 'Tomcat7' ...
    ......
    The service 'Tomcat7' has been installed.

    The Tomcat service called "Apache Tomcat 7" is installed and will start automatically whenever the system is started. Check the "Services" under "Control Panel" ⇒ "Administrative Tools".

    A GUI application called Tomcat7w is available for monitoring and configuring Tomcat services. Launch Tomcat7w:

    <CATALINA_HOME>\bin> Tomcat7w

    You could put the Tomcat icon in the system tray via the MS (Monitor Service) option:

    <CATALINA_HOME>\bin> Tomcat7w //MS//

    You can start/stop the Tomcat service now via:

    1. Tomcat7w;
    2. "Control Panel" ⇒ "Administrator Tools" ⇒ "Services" ⇒ "Apache Tomcat 7" ⇒ "Start";
    3. From CMD shell, Issue "net" command:
      prompt> net start tomcat7
      The Apache Tomcat 7 service is starting..
      The Apache Tomcat 7 service was started successfully.
      ......
      ......
      prompt> net stop tomcat7
      The Apache Tomcat 7 service is stopping..
      The Apache Tomcat 7 service was stopped successfully.

    To uninstall Tomcat Service, run the <CATALINA_HOME>\bin\service.bat with remove option:

    <CATALINA_HOME>\bin> service remove
    The service 'Tomcat7' has been removed

    You can also use Microsoft Management Console (MMC) to manage the services: Go to "Start" ⇒ ⇒ Run ⇒ enter "services.msc".

    A flip side of running Tomcat as a service is you need to read the error messages from <CATALINA_HOME>\logs instead of the Tomcat console.

    (Linux and Mac OS) Automatic Startup on Reboots

    To start Tomcat automatically when the machine boots up, you need to create a init script in /etc/init.d, e.g., /etc/init.d/tomcat, as follows:

    #!/bin/sh
    # Tomcat init script for Linux.
    #
    JAVA_HOME={path-to-java-installed-directory}
    CATALINA_HOME={path-to-Tomat-installed-directgory}
    export JAVA_HOME CATALINA_HOME
    exec $CATALINA_HOME/bin/catalina.sh $*

    Save the script as "tomcat" in /etc/init.d.

    $ cd /etc/init.d
    $ sudo chown root.root tomcat   // change owner to user root, group root
    $ sudo chmod 755 tomcat         // change mode u+rwx, g+rx, a+rx

    You can start|stop|restart Tomcat via:

    $ service tomcat start|stop|restart

    3.3  Tomcat's Startup Script

    To start tomcat server, you could invoke the batch file "startup.bat" (for Windows) or "startup.sh" (for Linux/Mac) (in directory "<CATALINA_HOME>\bin", where <CATALINA_HOME> refers to the Tomcat installed directory). The "startup.bat|startup.sh" invokes "catalina.bat start|catalina.sh start".

    Alternatively, you could call the "catalina.bat|catalina.sh" directly, which provides more options of starting Tomcat. Enter "catalina" to view the options:

    <CATALINA_HOME>/bin> catalina
    Using CATALINA_BASE:   D:\xxx\tomcat7.0.{xx}
    Using CATALINA_HOME:   D:\xxx\tomcat7.0.{xx}
    Using CATALINA_TMPDIR: D:\xxx\tomcat7.0.{xx}\temp
    Using JRE_HOME:        d:\xxx\jdk1.6
    Usage:  catalina ( commands ... )
    commands:
      debug             Start Catalina in a debugger
      debug -security   Debug Catalina with a security manager
      jpda start        Start Catalina under JPDA debugger
      run               Start Catalina in the current window
      run -security     Start in the current window with security manager
      start             Start Catalina in a separate window
      start -security   Start in a separate window with security manager
      stop              Stop Catalina
      configtest        Run a basic syntax check on server.xml
      version           What version of tomcat are you running?

    Study the source codes of "catalina.bat|catalina.sh". Take note that the environment variable JAVA_HOME is needed in this script.

    The other scripts provided are:

    • shutdown.bat|shutdown.sh: for shuting down the Tomcat server.
    • configtest.bat|configtest.sh: for checking the configuration file server.xml, same as "catalina configtest".
    • version.bat|version.sh: for displaying the versions, same as "catalina version".
    • digest.bat|digest.sh: making password hash and encrypting password.
    • Internal used: setclasspath.bat|setclasspath.shcpappend.bat (classpath append), tool-wrapper.bat|tool-wrapper.shdaemon.sh.

    4.  Security

    4.1  Realm and User Authentication in Tomcat

    References:

    1. "Realm Configuration HOW-TO" (@ "<CATALINA_HOME>\webapps\docs\realm-howto.html").
    2. "Java EE 5 Tutorial", Part IV "Services", Chapters 28-30 on Security.

    In Information Security:

    • Access control deals with identifying which resources require protection, and which users (roles) are authorized to access the protected resources.
    • Authentication deals with verifying users' credential, i.e., ensuring the user is "who he said he is". User's credential is typically provided in the form of username/password and possibly IP address (hostname). Other means include biometrics (finger-print, face recognition, retina) and digital certificates.
    • Confidentiality deals with the encryption of the transmitted data over the network. This is often carried out via employing HTTP over SSL (Secure Socket Layer), known as HTTPS.
    • Message Integrity ensures that messages are not tempered during transmission. This is done via message digest or hash.
    • Non-repudiation: If he/she has sent a message, he/she cannot deny. This is done via digital certificate and public/private keys.

    Security can be managed by the webapps themselves (called application-managed security) or via the Tomcat container (called container-managed security). In container-managed security, security is handled by the server. The server-side programs (servlets, JSPs) do not need any security-aware code. That is, the security control is totally transparent to the server-side programs. This section shall deal with container-managed security for access control and authentication.

    In Tomcat, a user is identified via username/password. A user is assigned role(s) (e.g., manager, admin, user, etc). Tomcat grants access for webapps to role(s), instead of individual users.

    realm is a collection of usernames/passwords and roles. Tomcat supports the following types of realms:

    • UserDatabaseRealm: kept in a XML file "conf\tomcat-users.xml", accessed via JDNI (Java Naming and Directory Interface).
    • JDBCRealm: kept in a relational database such as MySQL, accessed via JDBC.
    • others: JNDIRealm (uses LDAP directory), JAASRealm (Java Authentication and Authorization Service).

    You can used the <realm> element to configure a realm in "conf\server.xml". <realm> element can be placed in <engine><host>, or <context>, which determines the scope of the realm: all virtual hosts under the engine, a particular host, or a particular web application.

    4.2  UserDatabaseRealm

    UserDatabaseRealm stores user information in a XML file and accessed via JNDI (Java Naming and Directory Interface). By default, the XML file is "<CATALINA_HOME>\conf\tomcat-users.xml". UserDatabaseRealm is loaded into memory from the specified file, and kept in memory until Tomcat is shut down.

    Tomcat provide a JSP example called "FORM Authentication" (@ http://localhost:8080/examples/jsp/security/protected/index.jsp"), which uses UserDatabaseRealm. Let us study this example. But before we get into the codes, let's look at the Tomcat's configurations.

    "conf\server.xml"

    You can specify the type of realm to be used via <Realm> element in server.xml. In this case, UserDatabaseRealm. The <Realm> is defined within the <Engine> elements, and thus applicable to all the virtual hosts and webapps, under this server.

    To specify the file used in UserDatabaseRealm, a JDNI resource named "UserDatabase" is defined, which maps to the file "conf\tomcat-users.xml".

    <Server ...... >
      <!-- Global JNDI resources -->
      <GlobalNamingResources>
        <!-- Editable user database that can also be used by
             UserDatabaseRealm to authenticate users -->
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
                  description="User database that can be updated and saved"
                  factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                  pathname="conf/tomcat-users.xml" />
      </GlobalNamingResources>
      
      <Service name="Catalina">
        <Engine name="Catalina" defaultHost="localhost">
          <!-- Use the LockOutRealm to prevent attempts to guess user passwords
               via a brute-force attack -->
          <Realm className="org.apache.catalina.realm.LockOutRealm">
            <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                 resourceName="UserDatabase" />
          </Realm>
          <Host name="localhost" ......
            ......
          </Host>
        </Engine>
      </Service>   
    </Server>
    "conf\tomcat-users.xml"

    Recall that a user is identified via username/password. A user is assigned role(s). Accesses for web applications are granted to role(s) instead of individual users. "Tomcat-users.xml" contains the following roles and username/password, but commented-out. Uncomment them for testing the example. Two roles, tomcat and role1, and three users, tomcatrole1 and both are defined.

    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <tomcat-users>
      <role rolename="tomcat" />
      <role rolename="role1" />
     
      <user username="tomcat" password="tomcat" roles="tomcat" />
      <user username="both" password="tomcat" roles="tomcat,role1" />
      <user username="role1" password="tomcat" roles="role1" />
    </tomcat-users>
    

    Take note that the passwords are stored in clear text, which is not really desirable.

    "ContextRoot\WEB-INF\web.xml"

    For Tomcat's webapp called "examples", the security roles are defined using <security-constraint> element in "webapps\examples\WEB-INF\web.xml" as follows. The URL patterns /jsp/security/protected/* are accessible by users having roles of tomcat androle1 only.

    <web-app ......>
      ......
      <security-constraint>
        <display-name>Example Security Constraint</display-name>
        <web-resource-collection>
          <web-resource-name>Protected Area</web-resource-name>
          <!-- Define the context-relative URL(s) to be protected -->
          <url-pattern>/jsp/security/protected/*</url-pattern>
          <!-- If you list http methods, only those methods are protected -->
          <http-method>DELETE</http-method>
          <http-method>GET</http-method>
          <http-method>POST</http-method>
          <http-method>PUT</http-method>
        </web-resource-collection>
        <auth-constraint>
          <!-- Anyone with one of the listed roles may access this area -->
          <role-name>tomcat</role-name>
          <role-name>role1</role-name>
        </auth-constraint>
      </security-constraint>
      
      <!-- Default login configuration uses form-based authentication -->
      <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>Example Form-Based Authentication Area</realm-name>
        <form-login-config>
          <form-login-page>/jsp/security/protected/login.jsp</form-login-page>
          <form-error-page>/jsp/security/protected/error.jsp</form-error-page>
        </form-login-config>
      </login-config>
            
      <!-- Security roles referenced by this web application -->
      <security-role>
        <role-name>role1</role-name>
      </security-role>
      <security-role>
        <role-name>tomcat</role-name>
      </security-role>    
    

    4.3  HTML FORM-based Authentication Method

    The example uses HTML FORM-based authentication method, defined in element <login-config>. All accesses to the protected URLs (http://localhost:8080/examples/jsp/security/protected/*) will be redirected to the login.jsp page (defined in <form-login-page>), which prompts user for the credential. For example, if a user requests for http://localhost:8080/examples/jsp/security/protected/index.jsp, the login.jsp will be displayed.

    The login.jsp page contain a html <form> (thus called FORM-based authentication):

    <html>
    <head><title>Login Page for Examples</title></head>
    <body>
    <form method="POST" action='<%= response.encodeURL("j_security_check") %>' >
      Username:<input type="text" name="j_username">
      Password:<input type="password" name="j_password">
      <input type="submit" value="Log In">
    </form>
    </body>
    </html>

    The login page submits the username and password in parameters j_username and j_password to j_security_check<input type="password" ...> is used for password text field, which displays the password as *'s. The response.encodeURL(URL) encodes the URL j_security_check by including the session ID if URL-rewriting is used for session tracking; it returns the URL unchanged if cookie is used. For robust session tracking, all URLs emitted by server-side programs (servlet/JSP) should be run through this method.

    If login fails, user will be redirected to error.jsp page, as follows,

    <html>
    <head><title>Error Page For Examples</title></head>
    <body>
    Invalid username and/or password, please try again
    <a href='<%= response.encodeURL("index.jsp") %>'>again</a>.
    </body>
    </html>

    If login succeeds, the user will get the page he requested for. Study the "examples\jsp\security\protected\index.jsp" source.

    • To logoff, terminate the current session via session.invalidate().
    • You can use request.getRemoteUser() to get the authenticated login username; request.getUserPrincipal() to get a java.security.Principal object containing the name of the current authenticated user; request.isUserInRole(role) to check if the authenticated user is included in the specified role.

    4.4  HTTPS

    In FORM-based authentication, the username/password are sent in clear text, and susceptible to eavesdropping. Hence, it is important to encrypt the transport by turning on SSL (HTTPS). Read "Tomcat with SSL" on how to setup Tomcat with SSL.

    To enforce user to use secure transport (HTTPS), add a <transport-guarantee>CONFIDENTIAL</transport-guarantee>, inside the <security-constraint>, as follows:

    <security-constraint>
      <display-name>Example Security Constraint</display-name>
      <web-resource-collection>
        <web-resource-name>Protected Area</web-resource-name>
        <url-pattern>/jsp/security/protected/*</url-pattern>
        ......
      </web-resource-collection>
      <auth-constraint>
        <role-name>tomcat</role-name>
        ......
      </auth-constraint>
      <!-- must use SSL for secure transport -->
      <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
    </security-constraint>

    All accesses to HTTP at port 8080 (e.g., http://localhost:8080/examples/jsp/security/protected/index.jsp) will be redirected to HTTPS at port 8443 (e.g., https://localhost:8443/examples/jsp/security/protected/index.jsp).

    4.5  HTTP BASIC Authentication

    HTTP defines two access authentication schemes to request for username/password: Basic and Digest. Read "HTTP Authentication".

    To use BASIC authentication, change the <login-config>'s <auth-method> to BASIC.

    <login-config>
       <auth-method>BASIC</auth-method>
       <realm-name>Basic Authentication Area</realm-name>
       <!-- Removed, no applicable for BASIC authentication
       <form-login-config>
          <form-login-page>/jsp/security/protected/login.jsp</form-login-page>
          <form-error-page>/jsp/security/protected/error.jsp</form-error-page>
        </form-login-config>
        -->
    </login-config>

    In BASIC authentication, Tomcat uses the HTTP Basic Authentication to ask for username and password. Try http://localhost:8080/examples/jsp/security/protected/index.jsp, you will be prompted for username/password automatically. There is no redirect tologin.jsp and no need to write the login.jsp.

    Again, the HTTP Basic Authentication sends the username and password in clear text (password is encoded in Base64, but not encrypted). It is totally insecure, unless you use a secure transport (HTTPS) or VPN (Virtual Private Network).

    The Tomcat's webapp manager (under webapps/manager) uses BASIC authentication.

    4.6  HTTP DIGEST Authentication

    To use DIGEST authentation, change the <login-config>'s <auth-method> to DIGEST. In DIGEST authentication, Tomcat uses HTTP Digest Authentication Scheme to ask for username/password. Instead of sending password in clear text, the digest of password is send to the server. Although DIGEST authentication is more secure than BASIC authentication, HTTPS is much more secure.

    <login-config>
       <auth-method>DIGEST</auth-method>
       <realm-name>Digest Authentication Area</realm-name>
    </login-config>

    4.7  JDBCRealm

    UserDatabaseRealm is not meant for serious production environment, as it is hard to maintain. JDBCRealm is more appropriate.

    In JDBCRealm, user information is kept in a relational database, such as MySQL, accessed via JDBC, instead of an XML file. The information can be secured thruough proper database security.

    Setting up Database

    We shall set up our user database in MySQL. Read "How to Install MySQL and Get Started" if you are new to MySQL.

    The following script can be used to set up the user database. Two tables are required: a users table containing username and password, and a user_roles containing username and the role assigned.

    create database tomcat_users;
      
    use tomcat_users;
      
    create table users (
      username varchar(15) not null,
      password varchar(15) not null,
      primary key (username)
    );
      
    create table user_roles (
      username varchar(15) not null,
      role     varchar(15) not null,
      primary key (username, role)
    );
      
    insert into users values 
      ('tomcat', 'tomcat'), 
      ('both', 'tomcat'), 
      ('role1', 'tomcat');
      
    insert into user_roles values 
      ('tomcat', 'tomcat'), 
      ('role1', 'role1'), 
      ('both', 'tomcat'), 
      ('both', 'role1');
    JDBC Driver

    Next, copy the MySQL's JDBC driver ("mysql-connector-java-5.1.{xx}-bin.jar") into Tomcat's lib ("<CATALINA_HOME>\lib"). Read "How to Install MySQL and Get Started"

    "conf\server.xml"

    Again, the realm is defined in server.xml via a <Realm> element. In this case, a JDBCRealm, with a connectionURL providing a MySQL database connection.

    <Realm className="org.apache.catalina.realm.JDBCRealm"
       driverName="com.mysql.jdbc.Driver"
       connectionURL="jdbc:mysql://localhost:{port}/tomcat_users"
       connectionName="{dbuser}"
       connectionPassword="{dbpassword}"
       userTable="users" userNameCol="username" userCredCol="password"
       userRoleTable="user_roles" roleNameCol="role" />
    

    Replace the {port} with your MySQL server port number, and {dbuser} and {dbpass} with an authorized MySQL username/password.

    "ContextRoot\WEB-INF\web.xml"

    Same as UserDatabaseRealm.

    Authentication Methods

    Same as UserDatabaseRealm, you can use FORMBASIC or DIGEST authentication method.

    Testing

    You need to start MySQL server before starting the Tomcat Server.

    4.8  Single Login

    By default, each protected webapp would request for login during the first access. You can enable single login to all webapps under the host by uncommenting the single-login valve, as follows:

    <Host ......>
      <!-- SingleSignOn valve, share authentication between web applications
           Documentation at: /docs/config/valve.html -->
      <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    </Host>

    4.9  Tomcat with SSL

    SSL (Secure Socket Layer), allows web browsers and web servers to communicate over a secured (encrypted) connection. Tomcat provides built-in support for SSL.

    Read:

    • "SSL Configuration How-to" of Tomcat Documentation @ "<CATALINA_HOME>\webapps\docs\ssl-howto.html".
    • "keytool - Key and Certificate Management Tool" @ JDK documentation.

    The steps to turn on SSL support are:

    Step 1: Check your JDK version. Tomcat's SSL uses Java Secure Socket Extension (JSSE), which has been integrated into JDK since 1.4.

    Step 2: Prepare the Tomcat's server certificate, using the JDK's Key and Certificate Management Tool called "keytool" (in "<JAVA_HOME>\bin" ), as follows:

    > keytool
    ... display the help menu ...
     
    // Generate a self-signed certificate for Tomcat
    > keytool -genkey -alias tomcat -keyalg RSA -keystore {TOMCAT_HOME}\conf\.keystore
    Enter keystore password: xxxxxxxx
    Re-enter new password: xxxxxxxx
    What is your first and last name?
      [Unknown]:
    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=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
      [no]:  y
    Enter key password for <tomcat>
            (RETURN if same as keystore password):
    • The "-genkey" option is used to generate a public-private key pair. The public key is wrapped into an X.509 v1 self-signed certificate. The certificate and the private key are stored in a new keystore entry identified by the alias. In our case, the alias name must be "tomcat".
    • The "-keyalg" option specifies the key generation algorithm. RSA public key algorithm is used in this case.
    • The "-keystore" option specifies the name and location of the key store file.
    • The password for alias tomcat must be the same as the keystore (i.e., hit enter for the last question).

    Step 3: Enable SSL support for Tomcat. SSL is built into Tomcat. The Tomcat's configuration file commented out the SSL configuration directive. Uncomment them by removing the <!-- and --> around the SSL Coyote HTTP/1.1 Connector as follows:

    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
         SSLEnabled="true" maxThreads="150" scheme="https" secure="true"
         clientAuth="false" sslProtocol="TLS" 
         keystoreFile="{TOMCAT_HOME}\conf\.keystore"
         keystorePass="passwordOfKeyStore" />

    Note that the SSL (or HTTPS) is running on port 8443 instead of its default port number 443.

    Add in the keystoreFile and keyStorePass attributes. The keystoreFile attribute specified the location of the keystore file. The keyStorePass provides the password for accessing the keystore file.

    Step 4: Start your tomcat (run "<CATALINA_HOME>\bin\startup.bat"). After that, start a web browser and issue an HTTPS request as follows:

    https://localhost:8443
    

    5.  Clustering

    [TODO]

    5.1  Configuring Virtual Hosts

    To set up a virtual host called "www.mytest.com" (suppose that you have registered this hostname with at static IP address). Include the following <Host> element in server.xml under the Engine Catalina:

    <Engine name="Catalina" >
      <Host name="localhost .....>
        ......
      </Host>
      <Host name="www.mytest.com" appBase="webapps_mytest.com"
            unpackWARs="true" autoDeploy="true" >
        <Alias>mytest.com</Alias>
        <Valve className="org.apache.catalina.valves.AccessLogValve"
               directory="logs"
               prefix="mytest.com_access_log." suffix=".log"
               pattern="%h %l %u %t &quot;%r&quot; %s %b"
               resolveHosts="false" />
      </Host>
    </Engine>

    The above lines configure a virtual host with hostname "www.mytest.com", with webapps base directory at "<CATALINA_HOME>\webapps_mytest.com". We also define a alias called "mytest.com". That is, this host can be accessed via http://www.mytest.com:port orhttp://mytest.com:port. We also define a Valve, which intercepts the request message to write a log entries (similar to localhost).

    Next:

    1. Create a directory "webapps_mytest.com" under <CATALINA_HOME>, according to the appBase.
    2. Create a web application called ROOT, by creating a directory ROOT under the "webapps_mytest.com". Recall that ROOT was configured with an empty string URL. In other words, http://www.mytest.com:port/ accesses the ROOT application.
    3. Create a directory "www.mytest.com" under "conf\Catalina".
    4. Write a welcome page called "index.html" and save it in "webapps_mytest.com\ROOT".
      <html>
      <head><title>Testing Virtual Host</title></head>
      <body>
        <h1>It's work on virtual host</h1>
      </body>
      </html>

    To test the virtual host, without registering the hostname with an ISP, edit "C:\Windows\System32\drivers\etc\hosts" to include the following lines (required administrative authority):

    127.0.0.1   www.mytest.com
    127.0.0.1   mytest.com

    These lines maps host names www.mytest.com and mytest.com to IP address 127.0.0.1, which is the localhost. As the IP software checks the host file before asking Domain Name Service (DNS) to resolve a host name, you willl be able to test your virtual host.

    Now, you are ready to test the virtual hosts. Start the Tomcat server and issue these URL:

    http://www.mytest.com:8080
    http://mytest.com:8080
    http://www.mytest.com:8080/
    http://mytest.com:8080/
    http://www.mytest.com:8080/index.html
    http://mytest.com:8080/index.html

    5.2  Tomcat Host Manager for Clustering and Admin Roles

    Reference: "Clustering/Session Replication HOW-TO" @ "webapps/docs/cluster-howto.html".

    The Tomcat "host-manager" webapp allows you to manage Tomcat clusters. To access host-manager, you need to define a user with admin role.

    The admin role has been separated out as admin-gui and admin-script, in Tomcat 7, as defined in webapps/host-manager/WEB-INF/web.xml.

    The "Host Manager" web application can be accessed via http://{host}:{port}/host-manager/html.

    6.  Performance Tuning

    [TODO]

    REFERENCES & RESOURCES

    1. Tomcat mother site @ http://tomcat.apache.org
    2. Tomcat's Documentation @ "<CATALINA_HOME>\webapps\docs".
    3. Java Servlet, JavaServer Pages (JSP), and JavaServer Faces (JSF) specifications.

    List of Articles
    번호 제목 날짜 조회 수
    197 Tomcat 6에 Datasource 설정하기 2017.03.11 7720
    » tomcat - server.xml 설정 file 2017.03.11 99638
    195 [CentOS 6.5] Virtual Box를 이용한 CentOS 6.5 설치 file 2017.03.11 6694
    194 [CentOS 6.5] SSH,TELNET, FTP 설치 및 운용 file 2017.03.11 8720
    193 [CentOS 6.5] JDK (JAVA) 설치 file 2017.03.11 8776
    192 [CentOS 6.5] Tomcat 설치 및 구동 file 2017.03.11 9587
    191 TOMCAT/사이트 여러개 운영 2017.03.09 8516
    190 SSH / FTP 등 기본 접속환경 설정(리눅스 / 솔라리스) 2017.02.03 7947
    189 솔라리스 10 (Telnet/FTP/SSH) 설정 2017.02.03 8077
    188 아파치 디렉토리 보이는 것 막기 file 2017.02.02 8174
    187 아파치 로그(Apache Log) 관리법 2017.02.02 7944
    186 crontab 을 이용한 PHP 스케줄링 작업 file 2017.02.02 8600
    185 crontab 설정 방법 2017.02.02 7278
    184 apachec rewrite 사용하기 // www 강제 사용 // HTTP to HTTPS // 특정경로만 HTTP 2016.12.30 7158
    183 APACHE, OHS 400 웹로직 연동후 특정 작업에 400 error 2016.12.30 8774
    182 netstat 사용법 2016.12.22 8884
    181 mod_rewrite 예제 2016.12.22 7220
    180 아파치 웹로직 연동(Virtual Host) 2016.11.22 8629
    179 Apache 2.2.17 + WebLogic 10.3.3 연동하기 2016.11.22 8897
    178 CentOS6.6+httpd2.4.16+Mariadb10.0.20+php5.6.11 Source 설치.... file 2016.09.25 15312
    Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 12 Next
    / 12

    하단 정보를 입력할 수 있습니다

    © k2s0o1d4e0s2i1g5n. All Rights Reserved