본문 바로가기
JSP/이론

Servers // server.xml/context.xml

by SEOKIHOUSE 2023. 6. 27.
  • 1)server.xml

<GlobalNamingResources>는 Apache Tomcat과 같은 웹 애플리케이션 서버에서 사용되는 설정 요소 중 하나입니다. 이 요소는 전역적으로 사용 가능한 네임스페이스 리소스를 정의하는 데 사용됩니다.

<GlobalNamingResources> 섹션은 server.xml 파일 내에서 정의되며, 서버 전체에서 사용할 수 있는 리소스를 설정하는 데 사용됩니다. 이러한 리소스는 서버의 모든 웹 애플리케이션에서 공유되고 접근할 수 있습니다.

  • driverClassName : JDBC 드라이버 클래스명
  • type : 데이터소스로 사용할 클래스명
  • initialSize : 풀의 최초 초기화 과정에서 미리 만들어 놓을 연결의 개수(기본값은 0)
  • minldle : 최소한으로 유지할 연결 개수(기본값 0)
  • maxTotal : 동시에 사용할 수 있는 최대 연결 개수(기본값 8)
  • maxIdle : 풀에 반납할 때 최대로 유지될 수 있는 연결 개수(기본값 8)
  • maxWaitMillis : 새로운 요청이 들어왔을 때 얼마나 대기할지를 밀리초 단위로 기술
  • url : DB주소
  • username : 계정아이디
  • password : 계정비번
  • *name : 생성할 자원(여기서는 풀)의 이름

 

  • type="javax.sql.DataSource"
    서버가 시작되는 단계에서 미리 커넥션객체를 만들어놓고 연결요청이 오면
    미리 만들어진 객체를 제공(과부화 줄이도록 하려고)

ex)수영장 구명튜브 미리 만들어놓는 것  why? 올때마다 불어주면 힘드니깐 그런느낌ㅇㅇ


  • 2)Context.xml


  • 연결해보기

웹 애플리케이션에서 java:comp/env 컨텍스트를 통해 이 리소스에 접근할 수 있습니다.

톰캣에서 리소스를 관리하는 가상의 디렉토리 -java:comp/env 

package common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnPool {
	public Connection con;
	public Statement stmt;
	public PreparedStatement pstmt;
	public ResultSet rs;
	
	//기본생성자
	public DBConnPool() {
		try {
			//커넥션 풀(DataSource)얻기
			InitialContext initCtx = new InitialContext();
			//톰캣에서 자바를 이용할 때 고정적인 이름: java:comp/env
			Context ctx = (Context) initCtx.lookup("java:comp/env");
			DataSource source = (DataSource)ctx.lookup("dbcp.mydb");
			
			//커넥션 풀을 통해 커넥션 객체 얻기
			con = source.getConnection();
			System.out.println("DB 커넥션 풀 연결 성공");
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	// 연결해제(자원반납)
	public void close() {
		try {
			if (rs != null) 
				rs.close();
			if (stmt != null)
				stmt.close();
			if (pstmt != null)
				pstmt.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

server.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 --><Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!-- APR library loader. Documentation at /docs/apr.html -->
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
    
    
    <!--  
    <Resource auth="Container" driverClassName="org.mariadb.jdbc.Driver" initialSize="0" maxIdle="20" maxTotal="20" minIdle="5" maxWaitMillis="5000" name="dbcp/mydb" password="1234" type="javax.sql.DataSource" url="jdbc:mariadb://localhost:3306/green01" username="root"/>
     -->
     <!-- 
    <Resource auth="Container" driverClassName="org.mariadb.jdbc.Driver" initialSize="0" maxIdle="50" maxTotal="50" minIdle="5" name="dbcp/mydb" password="1234" type="javax.sql.DataSource" url="jdbc:mariadb://localhost:3306/green01" username="root"/>
     -->
    <Resource auth="Container" driverClassName="org.mariadb.jdbc.Driver" maxIdle="50" maxTotal="50" minIdle="5" name="dbcp/mydb" password="1234" type="javax.sql.DataSource" url="jdbc:mariadb://localhost:3306/green01" username="root"/>
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector connectionTimeout="20000" maxParameterCount="1000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               maxParameterCount="1000"
               />
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true"
               maxParameterCount="1000"
               >
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true"
               maxParameterCount="1000"
               >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector protocol="AJP/1.3"
               address="::1"
               port="8009"
               redirectPort="8443"
               maxParameterCount="1000"
               />
    -->

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine defaultHost="localhost" name="Catalina">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

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

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

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/>

      <Context docBase="0627practice_noajax" path="/0627practice_noajax" reloadable="true" source="org.eclipse.jst.jee.server:0627practice_noajax"/></Host>
    </Engine>
  </Service>
</Server>

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
        <ResourceLink global="dbcp.mydb" name="dbcp.mydb"
    			  type="javax.sql.DataSource"/>
</Context>