2021. 5. 3. 20:44ㆍJava/Spring
스프링 세팅 파일에는 대표적으로 3개의 xml 파일이 존재한다.
1. web.xml (세팅 파일 지정 및 기초 설정)
2. servlet-context.xml (서블릿 - 화면 이동에 관한 세팅)
3. applicationContext.xml (DB 정보 세팅)
web.xml 을 제외하고 설정 파일의 이름이 다를 수 있다.
가장 먼저 web.xml 을 설정해야한다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>sample22</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/servlet-context.xml
/WEB-INF/spring/aop-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>*.do</url-pattern> <!-- .do 링크는 무조건 controller로 이동 -->
</servlet-mapping>
<!-- DB 관련 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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>
<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>
web.xml 의 전체 코드는 위와 같다.
여기서 아래 코드를 통해 servlet 설정, 화면 이동 설정에 쓰일 파일을 지정한다. 그 외 AOP 같은 설정 파일들도 추가 가능하다.
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/servlet-context.xml
/WEB-INF/spring/aop-context.xml
</param-value>
</init-param>
서블릿 화면 이동에 쓰일 url pattern을 지정해주는데 *.do는 *.do 요청만 controller로 이동 시킨다.
/ 로 설정을 하면 모든 요청이 컨트롤러를 타게 된다. 해당 설정은 둘 중 하나만 적어줘도 무방하다.
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>*.do</url-pattern> <!-- .do 링크는 무조건 controller로 이동 -->
</servlet-mapping>
DB 관련 파일 세팅 파일을 지정해주기 위해 아래 코드로 파일을 지정해준다.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext.xml
</param-value>
</context-param>
이제 해당 설정 파일들을 확인을 해보자.
1. DB 세팅 파일 (applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- Database 설정 -->
<!-- db 초기화 파일의 위치/파일 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/jdbc.properties</value>
</list>
</property>
</bean>
<!-- DBMS(Database Management System) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="minIdle" value="${jdbc.initialSize}"/>
<property name="maxWait" value="3000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxOpenPreparedStatements" value="50"/>
</bean>
<!-- mybatis setting -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com.a.*.mapper/*.xml"/>
</bean>
<!-- sqlSession 취득 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
<constructor-arg index="1" value="SIMPLE"/> <!-- value="BATCH" -->
</bean>
<!-- jdbc 설정 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
먼저 DB 계정 정보가 적힌 파일을 불러와야한다.
<!-- db 초기화 파일의 위치/파일 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/jdbc.properties</value>
</list>
</property>
</bean>
위 설정으로 DB 설정 관련 정보를 불러오고 DB 세팅 정보를 아래와 같이 넣어준다.
<!-- DBMS(Database Management System) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="minIdle" value="${jdbc.initialSize}"/>
<property name="maxWait" value="3000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxOpenPreparedStatements" value="50"/>
</bean>
해당 파일에 정보가 다음과 같이 들어 있는데 해당 이름에 맞게 가져와서 값을 대입한다.
위 사진과 같이 id와 ref를 연결시켜서 bean 정보를 주입한다.
sqlsessionFactory는 dataSource에 저장 된 db 정보를 주입 받는다.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com.a.*.mapper/*.xml"/>
</bean>
해당 코드에서 calsspath 를 설정하는데 이 설정을 통해 쿼리가 쓰일 mapper 파일을 지정 가능하다. *을 사용함으로써 그 사이의 모든 폴더, 파일을 참조한다.
DB 세팅을 마무리 하고 두번째 servlet 화면에 대한 설정을 한다.
2. servlet-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- spring MVC annotation(주석문, 지시문)을 사용하기 위한 설정 -->
<context:annotation-config/>
<!-- viewResolver 설정(사용자의 view의 위치, 확장자 명 설정) -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
<property name="order" value="2"/>
</bean>
<!-- tiles 설정 -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/layouts.xml</value> <!-- jsp의 집합체 -->
</list>
</property>
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="requestContextAttribute" value="requestContext"/>
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"></property>
<property name="order" value="1"/>
<!-- <property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property> -->
</bean>
<!-- java 공통 패키지 -->
<context:component-scan base-package="com.a.*"/>
<!-- Ajax 주석문을 사용허가 -->
<mvc:annotation-driven/>
<!-- spring에서 처리할 수 없는 요청은 tomcat에 위임 -->
<mvc:default-servlet-handler/>
</beans>
먼저 컨트롤러가 리턴하는 화면의 형식을 지정해야한다.
이것을 viewResolver라고 부르는데 해당 세팅을 아래와 같이 해준다.
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
<property name="order" value="2"/>
</bean>
위와 같이 세팅을 해주면 컨트롤러의 리턴의 앞에는 자동으로 /WEB-INF/views/ 가 붙고, 맨 뒤에는 .jsp 가 붙어 자동으로 경로를 매핑한다.
EX) home => /WEB-INF/views/home.jsp
우리는 타일즈를 사용하기 위해서 아래의 세팅도 해준다.
<!-- tiles 설정 -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/layouts.xml</value> <!-- jsp의 집합체 -->
</list>
</property>
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="requestContextAttribute" value="requestContext"/>
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"></property>
<property name="order" value="1"/>
<!-- <property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property> -->
</bean>
먼저 타일즈 설정 파일의 위치를 지정해주고, 아래 코드는 컨트롤러가 타일즈를 거치도록 설정을 해준다.
위 코드에서 아래처럼 order가 있는데 이 코드는 컨트롤러의 요청을 먼저 타일즈(order = 1)를 거치게 하고, 타일즈 형식에 맞지 않으면 viewResolver(order = 2) 형태로 웹을 리턴한다.
컨트롤러의 리턴이 어떤 리졸버를 사용할지에 대한 우선순위 세팅이다.
<property name="order" value="1"/>
타일즈는 아래와 같이 세팅 가능하다.
3. layout.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<!--// main layout -->
<definition name="mainTiles" template="/WEB-INF/views/index.jsp">
<put-attribute name="header" value="/WEB-INF/views/include/header.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/include/footer.jsp" />
</definition>
<!-- 기본 메인-->
<definition name="index" extends="mainTiles">
<put-attribute name="body" expression="/WEB-INF/views/include/main.jsp" />
</definition>
<definition name="*/*" extends="mainTiles">
<put-attribute name="body" expression="/WEB-INF/views/{1}/{2}.jsp" />
</definition>
<definition name="*" extends="mainTiles" >
<put-attribute name="body" expression="/WEB-INF/views/{1}.jsp" />
</definition>
</tiles-definitions>
먼저 아래와 같이 타일즈가 기본 틀로 사용 할 파일을 선택한다.
<definition name="mainTiles" template="/WEB-INF/views/index.jsp">
<put-attribute name="header" value="/WEB-INF/views/include/header.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/include/footer.jsp" />
</definition>
여기서는 index.jsp가 해당 역할을 해준다. 해당 파일의 header에는 header.jsp가 footer에는 footer.jsp가 위치하게 된다.
위와 같이 찾아가는데 body의 값이 비어있다.
이 이유는 body는 페이지 이동시 변경이 되어야 하기 때문이다.
그래서 페이지 요청에 따라서 해당 파일을 찾아서 body안에 넣어주게끔 해야한다.
<!-- 기본 메인-->
<definition name="index" extends="mainTiles">
<put-attribute name="body" expression="/WEB-INF/views/include/main.jsp" />
</definition>
<definition name="*/*" extends="mainTiles">
<put-attribute name="body" expression="/WEB-INF/views/{1}/{2}.jsp" />
</definition>
<definition name="*" extends="mainTiles" >
<put-attribute name="body" expression="/WEB-INF/views/{1}.jsp" />
</definition>
맨 처음 index일시 최초 실행시 body를 main으로 지정한다.
만약 index가 아닐시 */* 요청일시 경로를 설정한다.
localhose:8080/user/usermain.do 요청이고 return 이 user/usermain이면
{1}에는 user가 오고, {2}에는 usermain이 와서
/WEB-INF/views/user/usermain.jsp 파일을 body에 넣어줘 화면을 보여준다.
이상으로 spring mvc 세팅 파일에 대한 설명 끝!
'Java > Spring' 카테고리의 다른 글
Spring - 카카오톡 로그인 기능 구현 하기 -2 (0) | 2021.05.10 |
---|---|
Spring - 카카오톡 로그인 기능 구현 하기 -1 (0) | 2021.05.10 |
Spring - 네이버 아이디로 로그인, 회원가입 만들기- 4 (1) | 2021.04.28 |
Spring - 네이버 아이디로 로그인, 회원가입 만들기- 3 (0) | 2021.04.28 |
Spring - 네이버 아이디로 로그인, 회원가입 만들기- 2 (1) | 2021.04.28 |