2018. 12. 26. 21:59



Spring Boot logo, brand

Spring boot

 

1. 설정


JDK version : 1.8

STS version : STS 3.9.7 RELEASE

(Eclipse version : Eclipse Java EE IDE for Web Developers)



이클립스 사용시 필수 플러그인

l  Spring Tools 3(aka Spring Tool Suite 3(STS))

l  BuildShip Gradle Integration 3.0

l  Gradle IDE Pack 3.8x+1.0x


(Maven 사용시 Gradle 관련 플러그인을 설치하지 않아도 무방)

(이클립스가 아닌 따로 STS(Spring Tool Suite)를 설치해서 사용해도 무방) 

STS 설치 주소:https://spring.io/tools3/sts/all

 


Eclipse Properties Setting

 

이클립스 상단 > File > Properties

General > Content Types > Text 아래 항목을 확인하여 Default Encoding UTF-8로 되어 있는지 확인하고 ISO-8859-1등 다른 Encoding으로 되어 있는 것이 있으면 전부 UTF-8로 변경

 

General > Workspace > Text file encoding : Other/UTF-8 로 변경

General > Workspace > New text file line delimeter : Other/Unix 로 변경

Web > CSS Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경합니다.

Web > HTML Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경

Web > JavaServer Faces Tool > Validation : 모든 Validate... 항목 해제

Web > JSP Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경

Web > JSP Files > Validate... 항목 해제

XML > XML Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경

 

General > Show heap status : 체크

General > Compare/Patch > Ignore white space : 체크

General > Editors > Text Editors > Show line numbers : 체크

General > Editors > Text Editors > Spelling > Enable spell checking : 해제

Java > Editor > Save Actions > Perform the selected actions on save : 해제

JavaScript > Editor > Save Actions > Perform the selected actions on save : 해제

Validation > Suspend all validators : 체크



출처http://javafactory.tistory.com/1466?category=618816 [FreeLife의 저장소]


 



1-1. Spring boot 프로젝트 생성하기



Package explorer > 우클릭 > new > other > spring starter project 검색 후 NEXT



Name > 프로젝트 이름 입력

(위 사진은 캡쳐용이라서 SpringBootTest_3가 아닌 SpringBootTest_1로 생성 해주세요)


Type > maven 선택 (Gradle 사용자 Gradle 선택)

(gradle이 좋다고 하지만 아직 익숙하지 않아 maven으로 예제 진행하겠습니다.)


Packaging > war


Group > package명 입력 (x.y 형식)


Artifact > Artifact명 입력 (프로젝트 이름과 동일(자동))


NEXT




web> web 선택 (다른 옵션들도 있지만 최초 생성 시에는 선택하지 않는게 좋다고 한다)

Finish

 

프로젝트 생성 후 jar를 파일들을 모두 가져올 때까지 기다린다.


프로젝트 생성 완료 후 모습


프로젝트 선택, 우 클릭 > Run as > Spring boot App 실행



1-2. 웹 브라우저 > localhost:8080 입력 후 아래 페이지가 나오는지 확인한다.





 


tip. Server port 설정 방법



src/main/resources/Application properties > server.port:포트번호 입력



2. Database 연동하기


예제에서는 MariaDBMybatis를 사용하여 진행하겠습니다.



2-0. database와 table 생성


mariaDB 실행 후 다음 쿼리 문 입력.


[database 생성]

create database testdb;


[table 생성]

create table t_list(

       SEQ int,

       ITEMID varchar(50)

);


[data 입력]

insert into t_list values (1, "A");

insert into t_list values (2, "B");

insert into t_list values (3, "D");

insert into t_list values (4, "E");

insert into t_list values (5, "H");




2-1 pom.xml 작성하기


[pom.xml]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        <!-- This is a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- This is for JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
 
        
        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId
        </dependency>
 
        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
 
        <!-- Need this to compile JSP, 
            tomcat-embed-jasper version is not working, no idea why -->
        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>
 
        <!-- Optional, test for static content, bootstrap CSS-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
        
        <!-- for mariaDB -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <!-- for mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
cs


위 dependency들을 pom.xml에 추가.



프로젝트 우클릭 후 Maven > Update Project 선택



해당 프로젝트 체크 후 'OK' 클릭 후 Update가 완료 될 때 까지 대기




2-2. application.properties 작성


2-2-1. datasource 설정


[src/main/resources > application.properties]

1
2
3
4
5
#mariaDB
spring.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/데이터베이스명
spring.datasource.username=사용자명
spring.datasource.password=
cs


line 2 : jdbc 설정

line 3 : 데이터베이스 설정 (DB에서 create database dbname;로 만든 것)

line 4 : 사용자 설정

line 5 : 비밀번호 설정



2-2-2 jsp 설정


1
2
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
cs


line 1 : 경로 설정

line 2 : 확장자 설정



2-2-3. application.properties에 설정한 경로대로 WEB-INF 폴더 생성

[src/main/webapp/WEB-INF/jsp]



jsp 폴더 안에 main.jsp와 dbTest.jsp 생성


[main.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
 
 
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>MAIN PAGE</title>
</head>
<body>
    <h1>THIS IS TEST PAGE</h1>
</body>
</html>
cs



[dbTest.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
 
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <table>
        <tr>
            <th>SEQ</th>
            <th>ITEMID</th>
        </tr>
 
 
        <c:forEach var="list" items="${list}">
            <tr>
                <td><p>${list.SEQ}</p></td>
                <td><p>${list.ITEMID}</p></td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
cs




2-3. DatabaseConfig 작성


Database에 접속하고 session을 관리하는 class를 생성해야함. 실제 DB에 대한 부분.


[com.example.SpringBootTest.DatabaseConfig.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.example.SpringBootTest;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(basePackages="com.example.SpringBootTest.dao")
@EnableTransactionManagement
public class DatabaseConfig {
 
    @Bean
    public  SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return sessionFactory.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
 
}
cs


@Configuration 

이 클래스는 Database 에 대한 접속 정보를 나타내고, 일반 Bean 이 나닌 Configuration으로 설정되어 있어야 한다. (실제로는 그 하위에 Bean을 두 개 더 생성한다)



@MapperScan(basePackages="com.simplify.sample")

최신 Spring Boot 에서는 dao를 dao라고 명시하지 않고, mapper 라는 이름으로 별도 정의하고 있다. 따라서 어떤 패키지에서 mapper들을 scan할 것인가를 최상위에 annotation으로 정의하여 주고 있다. 다중 Database에 접근해야 하는 경우, 이 클래스를 두 개를 만들어 두고 scan할 대상 mapper 들을 패키지 구조상에서 분리해 두는 것도 하나의 방법이라고 할 수 있다.



@EnableTransactionManagement

TransactionManager를 적용할 것인지에 대해 설정하는 annotation 이다.



@Bean SqlSessionFactory

DataSource 를 parameter로 받아, sqlSessionFactory를 생성하는 Bean 이다. 아래 있는 SqlSessionTemplate Bean 생성 시 인자로 넘겨주기 위해서 사용된다. 즉, 여기서 만들어진 기본정보, 설정값 등을 이용해서 SqlSessionTemplate를 만들게 되는 것이다.



.setMapperLocations()

실제 Query 문이 존재하는 xml파일들의 위치를 지정해 준다. 여기서는 mybatis/mapper 폴더 하위에 있는 모든 xml을 명시했다. 이 경로는 실제로는 src/main/resource 하위에 존재한다. ①이 폴더 구조 자체가 생성되어 있지 않거나, ②그 폴더에 mapper xml 이 하나도 없으면, ③혹은 그 xml 의 문법에 오류가 있으면 초기 구동 시점에 에러가 발생한다. 측, 초기에 mapper들의 위치 정보만을 지정하는 것이 아니라, 해당 mapper xml 들에 오류가 있는지 문법 체크까지 모두 한 뒤에 Factory가 생성되게 되는 것이므로, 이 부분을 다룰 때에는 중간중간 실행하여 오류가 발생하지는 않는지 꼭 확인하면서 지나가야 한다.



@Bean SqlSessionTemplate

실제 DB접속에 이용되는 SqlSessionTemplate를 생성하여 반환하는 Bean 이다. 실제 코드상에서 이용된다고 보면 된다.




여기까지 구현하고 실행하여 정상적으로 구동되는지 반드시 확인한다.


출처: https://4urdev.tistory.com/46 [Simplify]






2-4. DTO 클래스 작성


[com.example.SpringBootTest.dto.TestDTO]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.example.SpringBootTest.dto;
 
public class TestDTO {
    private int SEQ;
    private String ITEMID;
 
    public TestDTO() {
 
    }
 
    public TestDTO(int sEQ, String iTEMID) {
        super();
        SEQ = sEQ;
        ITEMID = iTEMID;
    }
 
    public int getSEQ() {
        return SEQ;
    }
 
    public void setSEQ(int sEQ) {
        SEQ = sEQ;
    }
 
    public String getITEMID() {
        return ITEMID;
    }
 
    public void setITEMID(String iTEMID) {
        ITEMID = iTEMID;
    }
 
}
 
cs


DB에 만들 컬럼명과 동일하게 생성할 것



2-5. DbMapper 인터페이스 작성


[com.example.SpringBootTest.dao.DbMapper]

1
2
3
4
5
6
7
8
9
10
package com.example.SpringBootTest.dao;
 
import java.util.List;
 
import com.example.SpringBootTest.dto.TestDTO;
 
public interface DbMapper {
    public List<TestDTO> getList() throws Exception;
}
 
cs






2-6. DbService 클래스 작성


[com.example.SpringBootTest.service.DbService]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.SpringBootTest.service;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.example.SpringBootTest.dao.DbMapper;
import com.example.SpringBootTest.dto.TestDTO;
 
@Service
public class DbService {
    
    @Autowired
    DbMapper dbmapper;
    
    public List<TestDTO> getList() throws Exception{
        
        return dbmapper.getList();
        
    }
}
 
cs






2-7. controller 클래스 작성


[com.example.SpringBootTest.controller]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.example.SpringBootTest.controller;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.example.SpringBootTest.dto.TestDTO;
import com.example.SpringBootTest.service.DbService;
 
@Controller
public class TestController {
 
    @Autowired
    DbService dbService;
    
    @RequestMapping("/")
    public String main() {
        return "main";
    }
    
    
    
    @RequestMapping("/dbTest")
    public ModelAndView dbTest() throws Exception {
        
        List<TestDTO> list = new ArrayList<TestDTO>();
        list = dbService.getList();
        
        
        
        return new ModelAndView("dbTest""list", list);
    }
}
 
cs





2-8. mapper.xml 작성


src/main/resources 에 mapper 폴더 생성 후 안에 databasemapper.xml 생성




[src/main/resources/mapper/databasemapper.xml]

1
2
3
4
5
6
7
8
9
10
<?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.example.SpringBootTest.dao.DbMapper">
    <select id="getList" resultType="com.example.SpringBootTest.dto.TestDTO">
        SELECT * FROM t_list
    </select>
</mapper>
 
 
 
cs


namespace는 mapper interface에 대한 풀 패키지 명을 입력.

resultType은 결과값의 타입을 입력한다. 예제의 반환 타입은 DTO객체이므로 DTO객체의 풀 패키지 명을 입력한다.


id는 mapper interface의 해당 쿼리문을 실행시킬 메서드명과 동일하게 작성한다.



모든 패키지와 파일들을 작성 완료 후 모습은 다음과 같다.






3. 실행


프로젝트 선택 후 우클릭 > Run As > Spring Boot App 선택






[Exception 발생 없이 실행이 완료된 모습]



웹 브라우저 주소창에 localhost:8282 입력





주소창에 localhost:8282/dbTest 입력



많이 부족한 포스팅이지만 궁금한 점이나 잘못된 점 있으면 댓글 남겨주세요!



 

'Web > Spring Framework' 카테고리의 다른 글

[Spring] Spring 개요  (0) 2018.11.28
Posted by PAYJAY