sin prisa pero sin pausa

[Spring] web.xml / root-context.xml / servlet-context.xml 본문

더 알아보고 싶은데?

[Spring] web.xml / root-context.xml / servlet-context.xml

EstherDmt 2021. 7. 19. 19:20
반응형

 1. web.xml 

https://www.sitesbay.com/servlet/servlet-web-xml

더보기

1. web.xml은 자바 Web application 설정파일(Configuration file)이다. 

2. WAS(Web Application Server)가 구동될 때 처음으로 읽어지는 파일이며 반드시 하나의 web.xml을 포함한다.

3. Web application 로딩 시 메모리에 로딩된다. 

4. 표준 deployment descriptor(배포 서술자) 이며, 브라우저가 자바 서블릿에 접근(요청, 응답받기)하기 위해

    로드되어야 하는 서블릿과 서블릿에 매핑되는 URL을 정의한다. 

    왜? WAS(ex.톰캣)은 서블릿을 관리하고 제어하는 주체이기 때문에 그에 대한 정보를 web.xml을 통해 알려주는 것

5. WEB-INF 디렉토리에 위치한다.

6. 서비스를 위한 필터와 인코딩, 서블릿 매핑을 정의한다.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://JAVA.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">

   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>


   <!-- web.xml 파일(배포 서술자) WAS(Web Application Server, Tomcat) 실행 시 제일 처음으로 
      읽어 들이는 파일. 서버 실행 시 초기에 설정 되어야하는 내용 또는 파일을 작성하여 설정 수행. + 서블릿 등록 및 URL패턴 지정 -->

   <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
   <!-- 밑에 작성된.xml에서 설정한 Bean은 모든 서블릿, 필터에서 공유 -->
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
      	classpath:spring/root-context.xml
      	classpath:spring/spring-security.xml
      </param-value>
   </context-param>


   <!-- Creates the Spring Container shared by all Servlets and Filters -->
   <!-- 서블릿과 필터에 공유 할 수 있도록 리스너를 설정 -->
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>

   <!-- Processes application requests -->
   <servlet>
      <servlet-name>appServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <!-- dispatcherServlet 생성 시, 서블릿 설정파일 로드 -->
         <param-value>classpath:spring/appServlet/servlet-context.xml
         </param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>

	<!-- dispatcherServlet 대한 url-pattern을 정의 
        /로 들어오는 모든 요청은 DispatcherServlet에서 처리 -->
   <servlet-mapping>
      <servlet-name>appServlet</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>


   <!-- 한글 깨짐 방지를 위한 Filter 추가 -->
   <!-- 별도의 filter 클래스를 만들지 않고 스프링에서 제공하는 filter를 사용 -->
   <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>
   </filter>
   <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>


</web-app>

 






 2. root-context.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<!-- Root Context: defines shared resources visible to all other web components -->

	<!-- root-context.xml 파일이란? 서버 구동 시 web.xml에서 가장 먼저 읽어들이는 설정 파일이다. DB 연결 
		정보, 트랜잭션 처리 관련 설정, 파일 업로드, AOP 등과 같이 프로젝트 전체에서 사용되는 내용을 작성한다. -->

	<!-- DBCP(Data Base Connection Pool) 사용을 위한 DataSource를 Bean으로 등록 -->
	<!-- DataSource란? : java에서 Connection Pool을 지원하기 위한 인터페이스 -->
	<!-- BasicDataSource : DataSource인터페이스를 구현한 클래스, 아파치 commons.dbcp에서 제공 -->
	<!-- destroy-method="close" : 주어진 세션을 자동으로 반환(close)하라는 설정 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp2.BasicDataSource"
		destroy-method="close">

		<property name="driverClassName"
			value="oracle.jdbc.driver.OracleDriver" />

		<property name="url"
			value="jdbc:oracle:thin:@localhost:1521:xe" />

		<property name="username" value="DB아이디" />

		<property name="password" value="DB비밀번호" />

		<!-- defaultAutoCommit: SQL 수행 후 자동 COMMIT 설정. (기본값 : true) -->
		<property name="defaultAutoCommit" value="false" />

		<!-- 커넥션 풀 설정 -->
		<property name="initialSize" value="10" /> <!-- 초기 커넥션 수, 기본 0 -->
		<property name="maxTotal" value="500" /> <!-- 최대 커넥션 수, 기본 8 -->
		<property name="maxIdle" value="100" /> <!-- 유휴 상태로 존재할 수 있는 커넥션 최대 수, 기본 8 -->
		<property name="minIdle" value="10" /> <!-- 유휴 상태로 존재할 수 있는 커넥션 최소 수, 기본 0 -->
		<property name="maxWaitMillis" value="-1" /> <!-- 예외 발생 전 커넥션이 반환 될 떄 까지 대기하는 최대 시간(ms), 기본 -1(무기한) -->
	</bean>



	<!-- SqlSession : sql구문을 DB에 전달, 실행하는 객체 
		 SqlSessionFactory : SqlSession을 만드는 객체 
		 sqlSessionFactoryBean : mybatis 설정 파일(mybatis-config.xml)과 Connection Pool 정보를 이용하여 SqlSessionFactory를 만드는 객체 
		 sqlSessionTemplate : SqlSession 객체에 트랜잭션 처리 역할이 가능하도록 하는 객체 -->
		 
	<!-- 마이바티스 SqlSession 등록하기 (xml 방식으로 bean 등록) -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<!-- mybatis-config.xml 설정 불러오기 -->
		<property name="configLocation"
			value="classpath:mybatis-config.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	
	<!-- SqlSessionTemplate : 기본 SQL 실행 + 트랜잭션 관리 역할을 하는 SqlSession을 생성할 수 있게 
		하는 객체(Spring bean으로 등록해야함.) -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">

		<constructor-arg ref="sqlSessionFactoryBean" />

	</bean>
	
	
	<!-- 스프링에서 사용하는 proxy를 이용한 트랜잭션 제어가 안될 경우 추가적인 트랜잭션 매니저를 추가해서 문제 해결 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

		<property name="dataSource" ref="dataSource" />

	</bean>
	
	<!-- @Transactional(commit/rollback 역할 할거임) 어노테이션을 인식 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
더보기

1. WAS 구동 시 web.xml에서 가장 먼저 읽어들이는 파일이다. 

2. 처음 만들어질 때는 아무것도 작성되어 있지 않다. 

3. DB연결, 트랜잭션 처리 관련 설정, 파일 업로드, AOP와 같이

Web application 전체에서 사용되는 내용이 작성된다.

4. root-context.xml에 등록되는 Bean들은 모든 context를 통해 공유가 가능하다.






 3. servlet-context.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />
	
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />
	<!-- image/html/js/css 등 정적인 파일 Get요청 할 때 mapping="주소"로 오도록 설정 -->
	
	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="edu.kh.fin" />
	
	
</beans:beans>
더보기

1. Servlet 단위로 생성되는 context이다.

2. DispatcherServlet 생성 시 설정 파일이다.

3. View(jsp)와 관련된 Bean 생성 설정 - Controller / View Resolver / Interceptor 등

4. component-scan 설정 - 지정된 패키지의 @Component를 스캔하여 Bean으로 등록한다.

5. annotation-driven 설정 - @Controller에 요청을 전달하기 위해 HandlerMapping 요소를 Bean으로 등록한다.

   component-scan에서 인식되는 위치들 중 어디로 전달될지 방향성이 정해진다.  

 


더보기

 번외 

context란?

스프링 Container 안에 Bean들을 직접 설정할 수 있는 공간을 뜻한다. 

각 서블릿에서 공통되는 Bean(DB연결, 트랜잭션 등-Service/Repository)을 root-context.xml에 포함하고 

각 서블릿마다의 설정 Bean(Controller/View)을 servlet-context.xml에 포함한다.

반응형