시작하기전에

  • STS나 jdk는 알아서 구글링 해서 준비할 것.
  • STS3
  • jdk 11

프로젝트 생성

프로젝트 생성 완료.


프로젝트 기본 세팅

window - preferences - General - Workspace 에서 Other: UTF-8로 변환


Project - properties - Resource 에서도 UTF-8 로 변환


톰캣연동

톰캣버전은 딱히 상관없다.

port 번호는 8090이든 8080이든 상관없음.

서버 더블클릭하고 Overview 와 Modules 둘 중에 Modules 를 누르면 위의 창이 나온다.

이렇게 바꿔주자.

한글이 안나오고 깨지는 경우가 있을텐데 그건 home.jsp 파일에 UTF-8 설정을 안해줘서 그렇다. 아직까진 상관 없다.

DB 생성

create database test;
  
use test;
  
  create table i_can_do_it(
  no int not null auto_increment primary key,
  id char(50) not null unique,
  name char(50),
  goal char(255),
  date date,
  time time
  );
  
insert into i_can_do_it(id, name, goal, date, time) values ('0113', '짱구', '부문장', now(), now());
insert into i_can_do_it(id, name, goal, date, time) values ('6378', '철수', '실장', now(), now());
insert into i_can_do_it(id, name, goal, date, time) values ('4963', '훈이', '파트장', now(), now());
insert into i_can_do_it(id, name, goal, date, time) values ('2978', '맹구', '사장', now(), now());
insert into i_can_do_it(id, name, goal, date, time) values ('7542', '유리', '정직원', now(), now());

select * from i_can_do_it;


web.xml 설정

  • 스프링 웹 프로젝트가 로딩될 때 가장 먼저 참조 되는 파일이다. 프로젝트의 환경 설정 정보를 저장하고 있는 파일이라고 생각하면 된다.
  • 그대로 복사해서 web.xml기존 내용을 다 지우고 이 코드를 넣어준다
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.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>
			<param-value>/WEB-INF/spring/appServlet/servlet-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>
	
	<!-- 한글 처리를 위한 인코딩 필터 -->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>


VO 생성

  • DB의 테이블 같은 형태의 VO(Value Object)를 생성하는 과정이다.
  • src/main/java 하위에 생성해준다.

방금 만든 패키지 안에 class 파일 생성

Date는 java.util.Date Time은 java.sql.Time로 임포트 해준다.

Getter and Setter 는 클래스 안에 private로 멤버 변수를 숨기고 public으로 개방된 메소드를 통해 이 변수에 간접적으로 접근하는 방법이다.

끝.


pom.xml

  • 기존에 있던 내용들을 다 지우고 이걸 복붙해준다.
  • 변경된 내용은 자바 버전을 1.8로 바꿨고 스프링 프레임워크를 4.3.18버전으로 바꾼 후 밑에 내려가보면 <!-추가-->라는 부분에서부터 mysql, mybatis등을 추가해주었다.
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.myproject</groupId>
	<artifactId>myapp</artifactId>
	<name>test_spring</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>4.3.18.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</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.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>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</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>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
		
		<!-- 추가 -->
		<!-- mysql -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>8.0.26</version>
		</dependency>    
		
		<!-- org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.1</version>
		</dependency>
		
		<!-- mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>1.3.0</version>
		</dependency>
		
		<!-- spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</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>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</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>


root-context.xml

이 항목 그대로 체크하고 저장해준다.


이어서 같은 root-context 에 source 로 들어가서 mysql 연동을 시킨다. ID 와 PW 부분은 각자의 ID와 PW 를 입력하면 된다.

봐도 모르겠으면 밑에 있는 코드를 복사 후 기존 내용을 지우고 붙여넣고 비밀번호 부분만 수정해주자.

<?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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://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">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
<!-- MySQL  -->
		<bean
		 class="org.springframework.jdbc.datasource.DriverManagerDataSource"
		 id="dataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
            value="jdbc:mysql://127.0.0.1:3306/test?useSSL=false&amp;serverTimezone=Asia/Seoul"></property>
        <property name="username" value="root"></property>
        <property name="password" value="비밀번호"></property>
		</bean>
	<!-- SqlSessionFactory  -->
		<bean id="sqlSessionFactory"
			 class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
	<!-- mybatis 설정파일의 경로 -->
		<property name="configLocation" value="classpath:/mybatis-config.xml" />
	<!-- mybatis mapper 파일의 경로 -->
		<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml" />
		</bean>
		
		<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
		
			<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
		</bean>		
</beans>


mybatis-config.xml

  • src/main/resources 하위에 mybatis-config.xml을 만들어준다.

이렇게 작성해준다.

<?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>
</configuration>


mappers 생성

  • src/main/resources 하위에 폴더를 만들어준다.
  • 나중에 mapper파일에 쿼리문을 작성한다.

xml 파일도 만들어준다.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.board.mappers.board">
</mapper>


테스트


만약 실행이 되지 않는다면 mybatis-config.xmlmappers 폴더를 확인해보자.

Leave a comment