You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
☸ k3d-rancher-cluster (default) in spring-boot-v20240120/tool/apache-tomcat-10.1.43
❯ cd conf
☸ k3d-rancher-cluster (default) in tool/apache-tomcat-10.1.43/conf
❯ ls
Catalina catalina.properties jaspic-providers.xml logging.properties tomcat-users.xml web.xml
catalina.policy context.xml jaspic-providers.xsd server.xml tomcat-users.xsd
☸ k3d-rancher-cluster (default) in tool/apache-tomcat-10.1.43/conf
❯ cat 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" />
--><!-- OpenSSL support using Tomcat Native --><Listener className="org.apache.catalina.core.AprLifecycleListener" /><!-- OpenSSL support using FFM API from Java 22 --><!-- <Listener className="org.apache.catalina.core.OpenSSLLifecycleListener" /> --><!-- 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 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><!-- 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 :
HTTP Connector: /docs/config/http.html
AJP Connector: /docs/config/ajp.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
--><Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxParameterCount="1000"
/><!-- 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 with HTTP/2
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"><UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /><SSLHostConfig><Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
certificateKeystorePassword="changeit" 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 name="Catalina" defaultHost="localhost"><!--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 name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="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"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" /></Host></Engine></Service></Server>
서블릿 컨테이너 초기화만 있어도 될 것 같은데, 왜 이렇게 복잡하게 애플리케이션 초기화라는 개념을 만들었을까?
편리함
서블릿 컨테이너를 초기화 하려면 ServletContainerInitializer 인터페이스를 구현한 코드를 만들어야 한다. 여기에 추가로 META-INF/services/jakarta.servlet.ServletContainerInitializer 파일에 해당 코드를 직접 지정해주어야 한다.
애플리케이션 초기화는 특정 인터페이스만 구현하면 된다.
의존성
애플리케이션 초기화는 서블릿 컨테이너에 상관없이 원하는 모양으로 인터페이스를 만들 수 있다. 이를 통해 애플리케이션 초기화 코드가 서블릿 컨테이너에 대한 의존을 줄일 수 있다. 특히 ServletContext ctx 가필요없는 애플리케이션 초기화 코드라면 의존을 완전히 제거할 수도 있다.
8️⃣ 스프링 컨테이너 등록
이번에는 WAS와 스프링을 통합해보자.
다음과 같은 과정이 필요
스프링 컨테이너 만들기
스프링MVC 컨트롤러를 스프링 컨테이너에 빈으로 등록하기
스프링MVC를 사용하는데 필요한 디스패처 서블릿을 서블릿 컨테이너 등록하기
dependencies {
//서블릿
implementation 'jakarta.servlet:jakarta.servlet-api:6.0.0'//스프링 MVC 추가
implementation 'org.springframework:spring-webmvc:6.0.4'
}
WebApplicationInitializer 인터페이스를 구현한 부분을 제외하고는 이전의AppInitV2Spring 과 거의 같은 코드이다.
WebApplicationInitializer 는 스프링이 이미 만들어둔 애플리케이션 초기화 인터페이스이다.
여기서도 디스패처 서블릿을 새로 만들어서 등록하는데, 이전 코드에서는 dispatcherV2 라고 했고, 여
기서는 dispatcherV3 라고 해주었다.
참고로 이름이 같은 서블릿을 등록하면 오류가 발생한다. servlet.addMapping("/") 코드를 통해 모든 요청이 해당 서블릿을 타도록 했다.
따라서 다음과 같이 요청하면 해당 디스패처 서블릿을 통해 /hello-spring 이 매핑된 컨트롤러 메
서드가 호출된다
현재 등록된 서블릿 다음과 같다.
/ = dispatcherV3
/spring/* = dispatcherV2
/hello-servlet = helloServlet
/test =TestServlet
이런 경우 우선순위는 더 구체적인 것이 먼저 실행된다.
✅ 스프링 MVC가 제공하는 서블릿 컨테이너 초기화 분석
스프링은 어떻게 WebApplicationInitializer 프링도 결국 서블릿 컨테이너에서 요구하는 부분을 모두 구현해야 한다. 인터페이스 하나로 애플리케이션 초기화가 가능하게 할까? 스프링도 결국 서블릿 컨테이너에서 요구하는 부분을 모두 구현해야 한다.
spring-web 라이브러리를 열어보면 서블릿 컨테이너 초기화를 위한 등록 파일을 확인할 수 있다. 그리고 이곳에 서블릿 컨테이너 초기화 클래스가 등록되어 있다.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
섹션 3. 웹 서버와 서블릿 컨테이너
1️⃣ 웹 서버와 스프링 부트 소개
2️⃣ 톰캣 설치

plugins { id 'java' id 'war' } group = 'hello' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' repositories { mavenCentral() } dependencies { //서블릿 implementation 'jakarta.servlet:jakarta.servlet-api:6.0.0' } tasks.named('test') { useJUnitPlatform() }3️⃣ 프로젝트 설정
4️⃣ WAR 빌드와 배포
plugins { id 'java' id 'war' }✅ WAR 압축 풀기
✅WAR를 푼 결과
✅ JAR, WAR 간단 소개
JAR소개
WAR 소개
웹 애플리케이션 서버 위에서 실행되고, HTML 같은 정적 리소스와 클래스 파일을 모두 함께 포함하기 때문에 JAR와비교해서 구조가 더 복잡함.
주의사항 - WAR 구조를 지켜야 한다.
✅WAR 구조
WEB-INF
index.html : 정적 리소스
WEB-INF 폴더 하위는 자바 클래스와 라이브러리, 그리고 설정 정보가 들어가는 곳이다.
WEB-INF 를 제외한 나머지 영역은 HTML, CSS 같은 정적 리소스가 사용되는 영역이다.
➡️ WAR 배포
생성된 WAR파일을 톰캣 서버에 실제 배포해보자.
./shutdown.sh톰캣폴더/webapps하위를 모두 삭제한다.server-0.0.1-SNAPSHOT.war를 복사한다.톰캣폴더/webapps하위에 붙여넣는다.톰캣폴더/webapps/server-0.0.1-SNAPSHOT.war톰캣폴더/webapps/ROOT.war./startup.sh5️⃣ 톰캣 설정 - 인텔리제이 J 유료 버전
6️⃣ 서블릿 컨테이너 초기화 1
✅ 서블릿 컨테이너 초기화 개발
ServletContainerInitializer라는 초기화 인터페이스를 제공한다.onStartup()을 호출해준다. 여기서 애플리케이션에 필요한 기능들을 초기화 하거나 등록할 수 있다.7️⃣ 서블릿 컨테이너 초기화 2
✅ 서블릿을 등록하는 2가지 방법
@WebServlet 애노테이션 → 앞서 했던 방법
프로그래밍 방식 → 이번에 할 것
HelloServlet.java
➡️ 애플리케이션 초기화
서블릿 컨테이너는 조금 더 유연한 초기화 기능을 지원한다.
여기서부터 이것을 애플리케이션 초기화라 하겠다.
실제 동작하는 코드를 보고 이해해보자.
AppInit.interface
🗒️ 참고 - 프로그래밍 방식을 사용하는 이유
➡️ AppInit는 어떻게 실행되는 것일까?
✅ 애플리케이션 초기화 과정
ServletContainerInitializer)는 파라미터로 넘어오는 Set<Class<?>> c에 애플리케이션 초기화 인터페이스의 구현체들을 모두 찾아서 클래스 정보로 전달한다.➡️MyContainerInitV2 등록
✅ 그림으로 정리
✅ 참고
8️⃣ 스프링 컨테이너 등록
이번에는 WAS와 스프링을 통합해보자.
다음과 같은 과정이 필요
dependencies { //서블릿 implementation 'jakarta.servlet:jakarta.servlet-api:6.0.0' //스프링 MVC 추가 implementation 'org.springframework:spring-webmvc:6.0.4' }심플한 스프링 컨트롤러
실행하면 HTTP 응답으로 Hello Spring! 반환
HelloConfig
컨트롤러를 스프링 빈으로 직접 등록
AppInitV2Spring
AppInitV2Spring는 AppInit을 구현했다. AppInit을 구현하면 애플리케이션 초기화 코드가 자동으로 실행된다. 앞서 MyContainerinitV2에 관련 작업을 미리 해둠.
스프링 컨테이너 생성
스프링 MVC 디스패처 서블릿 생성, 스프링 컨테이너 연결
빈들을 호출한다.
디스패처 서블릿을 서블릿 컨테이너에 등록
🚨 주의 - 서블릿을 등록할 때 이름은 원하는 이름을 등록하면 되지만 같은 이름으로 중복 등록하면 오류가 발생한다. 여기서는 dispatcherV2 이름을 사용했는데, 이후에 하나 더 등록할 예정이기 때문에 이름에 유의하자
결과
✅ 실행 과정 정리
러를 찾는다.)
9️⃣ 스프링 MVC 서블릿 컨테이너 초기화 지원
ServletContainerInitializer인터페이스를 구현해서 서블릿 컨테이너 초기화 코드를 만들었다.컨테이너 초기화 클래스 경로를 등록했다.
서블릿 컨테이너 초기화는 정말 귀찮다. 반복되는 작업이면서 번거롭다.
그러한 단점을 극복한게 스프링 MVC이다. MVC는 서블릿 컨테이너 초기화 작업을 이미 만들어두었다. 덕분에 개발자는 서블릿 컨테이너 초기화 과정은 생략하고, 애플리케이션 초기화 코드만 작성하면 된다.
WebApplicationInitializer인터페이스를 구현한 부분을 제외하고는 이전의AppInitV2Spring과 거의 같은 코드이다.WebApplicationInitializer는 스프링이 이미 만들어둔 애플리케이션 초기화 인터페이스이다.여기서도 디스패처 서블릿을 새로 만들어서 등록하는데, 이전 코드에서는
dispatcherV2라고 했고, 여기서는
dispatcherV3라고 해주었다.참고로 이름이 같은 서블릿을 등록하면 오류가 발생한다.
servlet.addMapping("/")코드를 통해 모든 요청이 해당 서블릿을 타도록 했다.따라서 다음과 같이 요청하면 해당 디스패처 서블릿을 통해
/hello-spring이 매핑된 컨트롤러 메서드가 호출된다
/= dispatcherV3/spring/* = dispatcherV2helloServlet/test =TestServlet✅ 스프링 MVC가 제공하는 서블릿 컨테이너 초기화 분석
WebApplicationInitializer프링도 결국 서블릿 컨테이너에서 요구하는 부분을 모두 구현해야 한다. 인터페이스 하나로 애플리케이션 초기화가 가능하게 할까? 스프링도 결국 서블릿 컨테이너에서 요구하는 부분을 모두 구현해야 한다.spring-web라이브러리를 열어보면 서블릿 컨테이너 초기화를 위한 등록 파일을 확인할 수 있다. 그리고 이곳에 서블릿 컨테이너 초기화 클래스가 등록되어 있다.✅ SpringServletContainerInitializer
WebApplicationInitializer이다 그리고 인터페이스의 구현체를 생성하고 실행하는 것을 확인할 수 있다. 우리는 앞서 이 인터페이스를 구현했다.✅ 정리
Beta Was this translation helpful? Give feedback.
All reactions