Spring MVC Maven 프로젝트 설계

hyeokjin·2022년 2월 17일
0
post-thumbnail

Spring Maven 프로젝트를 생성하여 MVC패턴을 구현하기 위한 설계/개발을 했을 때, 기본적인 내용들을 정리해 보고자 한다

🔨[준비물]

java 1.8 ver
이클립스 photon
PostgreSQL
tomcat 8 or 9

🔨[환경세팅]

1. HyeokJin이라는 프로젝트 생성
(이클립스 photon 버전에 sts(spring tool) 다운로드가 할 수 없어서
다이나믹 프로젝트를 만들고 메이븐을 추가 설정하여 Spring Maven 형태로 변환하여 만듬)

2. tomcat 설치 및 서버등록

3. pom.xml에서 필요한 라이브러리 dependency 추가 및 logback 추가
(springframework, annotation, lombok, jdbc, jquery, jstl, json, postgresql,mybatis 등등)

4. web.xml에서 dispatcherServlet 맵핑, ServletContext.xml 생성, 인코딩 한글 설정

5. ServletContext.xml에서 뷰리졸버 등록 및 어노테이션 설정, 정적파일(이미지, 사운드, 동영상, JS, CSS 등등) 경로 셋팅

6. root-context.xml 생성 후 mybatis MapperScaner(@Mapper 사용), xml 경로 셋팅 및 postgreSql db 연결 설정

7. controller, mapper, service, serviceImpl, vo 등 만들고 어노테이션을 이용해 REST API 구현
(MyBatis에서 mapper대신 DAO를 만들어서 sqlSession을 통해 xml과 연결하여 조회했다면 이번엔 interface mapper를 만들어서 @Mapper를 이용하여 xml과 연결)
-> @Mapper 장점
sqlSession을 사용했을 때 메서드를 상황에 따라 직접 호출하면서 메서드 명을 알아야 하는데에 반해, 호출을 이용해 SQL을 실행시키기 때문에 sqlSession의 메서드를 몰라도 된다.


🔻 설정 파일은 다음과 같다
(pom.xml 경우, 기존에 만들었던 셋팅파일로 dependency 추가한 것이 많기 때문에 감안해서 보면 된다.)

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>HyeokJin</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <url>http://maven.apache.org</url>
  
	<properties>
		<!-- spring -->
		<org.springframework-version>4.3.18.RELEASE</org.springframework-version>
		
		<!-- slf4j -->
		<org.slf4j-version>1.6.6</org.slf4j-version>

		<!-- jdk -->
		<java-version>1.8</java-version>

		<!-- mybatis -->
		<mybatis.version>3.4.6</mybatis.version>
		<mybatis.spring.version>1.3.2</mybatis.spring.version>
		
	</properties>
 
	<dependencies>
		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <version>4.0.1</version>
		    <scope>provided</scope>
		</dependency>
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jsp-api</artifactId>
		    <version>2.0</version>
		    <scope>provided</scope>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-beans</artifactId>
		    <version>5.2.3.RELEASE</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>5.2.3.RELEASE</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-core</artifactId>
		    <version>5.2.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>5.2.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.2.3.RELEASE</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
		<dependency>
		    <groupId>javax.annotation</groupId>
		    <artifactId>javax.annotation-api</artifactId>
		    <version>1.3.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/taglibs/standard -->
		<dependency>
		    <groupId>taglibs</groupId>
		    <artifactId>standard</artifactId>
		    <version>1.1.2</version>
		</dependency>
		
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
		<dependency>
		    <groupId>javax.mail</groupId>
		    <artifactId>mail</artifactId>
		    <version>1.4.4</version>
		</dependency>
		<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- org.json -->
		<dependency>
		    <groupId>org.json</groupId>
		    <artifactId>json</artifactId>
		    <version>20180130</version>
		</dependency>

		<!-- Jackson JSON Mapper start -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.9.3</version>
		</dependency>
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-core</artifactId>
		    <version>2.9.6</version>
		</dependency>
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.9.6</version>
		</dependency>
		<!-- Jackson JSON Mapper end -->

        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1 </version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator</artifactId>
            <version>0.40</version>
        </dependency>

		<!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.16</version>
			<scope>provided</scope>
		</dependency>

		<!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-dbcp2</artifactId>
		    <version>2.4.0</version>
		</dependency>
		
		<dependency>
		    <groupId>org.postgresql</groupId>
		    <artifactId>postgresql</artifactId>
		    <version>42.2.25</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.jdatepicker/jdatepicker -->
		<dependency>
		    <groupId>org.jdatepicker</groupId>
		    <artifactId>jdatepicker</artifactId>
		    <version>1.3.4</version>
		</dependency>

		<!-- Logging -> slf4j(interface) -> logback(slf4j 구현체) -->
		<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-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</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>
		<dependency>
	        <groupId>ch.qos.logback</groupId>
	        <artifactId>logback-classic</artifactId>
	        <version>1.1.2</version>
	        <exclusions>
	            <exclusion>
	                <groupId>org.slf4j</groupId>
	                <artifactId>slf4j-api</artifactId>
	            </exclusion>
	        </exclusions>
	    </dependency>
	</dependencies>
  
  <build>
<!--     <sourceDirectory>src</sourceDirectory> -->
    <plugins>
      <plugin>
      	<groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
      	<groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.1</version>
        <configuration>
          <warSourceDirectory>webapp</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

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" 
id="WebApp_ID" version="3.1">

  <display-name>HyeokJin</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<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/servletContext.xml</param-value> 
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

  	<!-- 서블릿과 필터에 공유할 수 있는 리스너 설정 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 한글 설정 -->
	<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>

servletCntext.xml

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

	<context:component-scan base-package="com"/>
  
	<!-- <resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/> -->
	<!-- 정적파일(이미지, 사운드, 동영상, JS, CSS 등등) 경로 셋팅 -->
	<mvc:resources mapping="/resources/**" location="/resources/" /> 
	<mvc:resources mapping="/js/**" location="/resources/js" />
	<mvc:resources mapping="/css/**" location="/resources/css" />
	<mvc:resources mapping="/admin/**" location="/resources/admin" />
	<mvc:resources mapping="/images/**" location="/resources/images" />
	<mvc:resources mapping="/smartEditor/**" location="/resources/smartEditor" />


	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 첨부 파일 업로드  MultipartResolver 추가 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20000000" />
    </bean>

</beans>

root-context.xml

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

	<!-- PostgreSQL JDBC setting -->
  	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
	    <property name="driverClassName" value="org.postgresql.Driver" />
	    <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
	    <property name="username" value="postgres"/>
	    <property name="password" value="P@ssw0rd"/>
	</bean>

	<!-- mybatis setting -->
 	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	    <property name="dataSource" ref="dataSource" />
	    <!-- <property name="configLocation" value="/WEB-INF/config/mybatis-config.xml" /> -->
	    <property name="mapperLocations" value="classpath:/mapper/*.xml" />
		<!-- 트랜잭션 관리를 위한 것 -->
	    <property name="transactionFactory">
	    	<bean class="org.mybatis.spring.transaction.SpringManagedTransactionFactory" />
	    </property>
	</bean>

    <!-- scan for mappers -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.**.mapper" />
        <property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

	<context:component-scan base-package="com">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
</beans>


해당 프로젝트에서 추가적으로 Rest api 구현한 소스는 깃헙사이트에서 확인하면 된다.
https://github.com/hyeokjinON/Spring_MVC.git

profile
노옵스를향해

0개의 댓글