Spring Legacy 기본 설정 코드

최주영·2023년 7월 10일
0

spring

목록 보기
3/12

web.xml
web.xml은 설정을 위한 설정 파일이다.
WAS가 처음 구동될 때 web.xml을 읽어 웹 애플리케이션 설정을 구성한다.
여러 XML파일을 인식하도록 각 파일을 가리킨다
-> servlet-context.xml root-context.xml 등등..어디서 가져올건지 인식해줌
DispatcherServlet을 등록해주면서 스프링 설정 파일을 지정한다.
DispatcherServlet은 초기화 과정에서 지정된 설정 파일을 이용해 스프링 컨테이너를 초기화 싴팀
모든 요청을 DispatcherServlet이 처리하도록 서블릿 매핑을 설정
Web.xml에서는 크게 DispatcherServlet, ContextLoaderListener, Filter 설정을 함

  • DispatcherServlet : 클라이언트의 요청을 처리하는 객체
    -> 클라이언트 요청 처리하는 4가지 순서
    첫째, 클라이언트의 요청을 처리해줄 컨트롤러를 찾는다.
    둘째, 컨트롤러를 실행시킨다. (비지니스 로직 처리)
    셋째, 클라이언트에게 보여질 View를 찾는다.
    넷째, 응답 데이터와 View를 클라이언트에게 전달한다.

  • ContextLoaderListener : 모든 서블릿이 공통으로 가져야할 설정을 지정
    -> Controller가 공유하는 Bean들을 포함하는 Spring Container를 생성
    -> WAS구동시에 web.xml을 읽어들여 웹 어플리케이션 설정을 구성 , 초기셋팅작업 을 해주는 역할
    ex) root-context.xml

  • Filter : 클라이언트에서 온 요청을 Dispatcher Servlet이 받기 전 거치는 부분
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee                       http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring/root-context.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> 
    <!--  contextConfigLocation : 스프링프레임 워크가 동작하기 위한 설정파일의 위치를 알려주는 파라미터 -->
			<param-value>
		    /WEB-INF/spring/root-context.xml     	
			/WEB-INF/spring/security-context.xml  
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 
		인코딩필터 등록하기 
		spring이 encodingFilter클래스를 제공함	
	-->
	<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> <!-- 모든부분에 encoding 처리함 -->
	</filter-mapping>
</web-app>

root-context.xml
이 context에 등록되는 Bean들은 모든 context에서 사용되어 진다(공유가 가능)
Service, Repository(DAO), DB등 비즈니스 로직과 관련된 설정을 해줌

<?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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<!-- DB연결하는 객체 bean으로 등록하기 -->
	<!-- 
		1. DataSource 클래스 -> DB에 접속하는 정보를 제공해주는 bean -> BasicDataSource 클래스
		2. SqlSessionFactory 클래스 -> SqlSession을 생성해주는 클래스 -> SqlSessionFactoryBean 클래스
		3. SqlSession 클래스 -> 사용하는 클래스(SQL 실행, connection 관리) -> SqlSessionTemplate 클래스
	 -->	
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- destroy-method (닫아줘야하므로) 설정 -->
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
		<property name="username" value="spring"/>
		<property name="password" value="spring"/>
	</bean>
		
	<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="classpath:mybatis-config.xml"/>
		<property name="mapperLocations" value="classpath:mappers/**/*.xml"/>
		<!--  * : 바로밑에있는거 다,  ** : 하위에있는거 모두 다 -->	
	</bean>	
	
	
	<bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sessionFactory"/>
	</bean>
		
</beans>

스프링 컨테이너
스프링 프레임워크의 핵심 컴포넌트
자바 객체의 생명 주기를 관리(빈의 생성, 관리, 제거 등)하며, 생성된 자바 객체들에게 추가적인 기능을 제공
스프링에서는 자바 객체를 (Bean)이라 한다.
스프링컨테이너는 XML, 어노테이션 기반의 자바 설정 클래스로 만들 수 있다.
스프링 부트(Spring Boot)를 사용하기 이전에는 xml을 통해 직접적으로 설정해 주어야 했지만, 스프링 부트가 등장하면서 대부분 사용 하지 않게 되었다.
스프링컨테이너의 종류 -> (빈팩토리, 어플리케이션컨텍스트)
빈 팩토리(BeanFactory)는 스프링 컨테이너의 최상위 인터페이스

viewResolver
사용자의 요청에 대한 응답 view를 렌더링 하는 역할
prefix는 렌더링 시 handelr에서 반환하는 문자열의 에 붙여줄 문자열을 의미하고
suffix는 뒷쪽에 붙는 문자열

✅ 프로젝트 업데이트 단축키
alt + f5
프로젝트 우클릭 -> Maven -> update project


servlet-context.xml
이 context에 등록되는 Bean들은 servlet-container에만 사용되어진다
web.xml에서 DispatcherServlet 등록 시 설정한 파일이다.
앞서 설명한 것 처럼 설정 파일을 이용해서 스프링 컨테이너를 초기화시킨다.

<?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"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd
		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/" /> 
  <!-- /resources/** 라는 요청이오면 /resources/ 경로로 잡아주라는 뜻 -->

	<!-- 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="com.bs.spring"/>
	
	
	<!-- 
		pojo클래스 bean으로 등록하기 
		<beans:bean>태그를 이용해서 등록
			속성 
			id : context 내에서 사용하는 bean이름
			class : 대상이되는 클래스지정(패키지명.클래스명)	
	-->
	<!-- Animal 클래스를 default 생성자로 생성해서 bean으로 등록 -->
	<!-- <beans:bean id="bbo" class="com.bs.spring.beantest.Animal"/> --> <!-- xml파일로 클래스 등록하는 방법 -->
	 
	<!-- pojo생성시 setter를 이용해서 데이터를 넣어서 생성시키기 -->
	<beans:bean id="bbo" class="com.bs.spring.beantest.Animal">
		<beans:property name="name" value="뽀숑"/> 
		<beans:property name="age" value="3"/>
		<beans:property name="height" value="50.4"/> 

	</beans:bean>
	
	
</beans:beans>

pom.xml : Maven의 빌드 정보를 담고 있는 파일

  • <project> : Maven의 XML 네임스페이스를 지정
  • <modelVersion> : Maven의 model Version
  • <groupId> : 그룹 ID태그
  • <artifactId> : 아티팩트ID 태그
  • <version> : 버전명 태그
  • <packaging> 패키징 형식을 지정하는 태그
  • <name> : 프로젝트의 이름
  • <url> : Maven의 url
  • <properties> : 프로젝트 관련 속성
  • <parent> : pom.xml의 상속에 관련된 태그
  • <dependencies> : 프로젝트가 의존하는 라이브러리들의 정보
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bs</groupId>
  <artifactId>spring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>spring</name>
  
  	<properties>
		<java-version>17</java-version>
		<org.springframework-version>5.3.28</org.springframework-version>
		<org.aspectj-version>1.9.19</org.aspectj-version>
		<org.slf4j-version>2.0.7</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
						
		
		<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
		<dependency>
		    <groupId>jakarta.servlet</groupId>
		    <artifactId>jakarta.servlet-api</artifactId>
		    <version>4.0.4</version>
		    <scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
		<dependency>
		    <groupId>javax.servlet.jsp</groupId>
		    <artifactId>javax.servlet.jsp-api</artifactId>
		    <version>2.3.3</version>
		    <scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jstl</artifactId>
		    <version>1.2</version>
		</dependency>
		
		<!-- 롬복 등록-->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.28</version>
		    <scope>provided</scope>
		</dependency>

		
		
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
  
</project>

mybatis-config.xml
typeAliases : 매칭할 mapper의 sql태그의 parmeter Type 별칭 설정
mapper의 sql 태그의 type(parmeter Type)을 alias로 설정

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
	<typeAliases>
		<typeAlias type="com.bs.spring.demo.model.dto.Demo" alias="demo"/>
		<typeAlias type="com.bs.spring.member.Member" alias="member"/>
		<typeAlias type="com.bs.spring.common.StringArrayTypeHandler" alias="strArr"/>
	</typeAliases>
	
</configuration>

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p : %l - %m%n" />
		</layout>
	</appender>
		<!-- Application Loggers -->
	<logger name="com.bs.spring">
		<level value="debug" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.beans">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="info" />
	</logger>

	<logger name="org.springframework.web">
		<level value="info" />
	</logger>

	<!-- Root Logger -->
	<root>
		<priority value="warn" />
		<appender-ref ref="console" />
	</root>
</log4j:configuration>
profile
우측 상단 햇님모양 클릭하셔서 무조건 야간모드로 봐주세요!!

0개의 댓글