khann's IT와 경제 블로그

반응형

인텔리제이에서 스프링 MVC + MariaDB 세팅하기 maven (spring on intellij)

 

 

환경

운영체제 : Windows 10

JDK : 9.0.4

IDE : Intellij IDEA ULTIMATE

프레임워크 : Spring MVC(4.3.18.RELEASE) + MAVEN(5.2.3.RELEASE)

서버 : Tomcat (7.0.105)

DB : MariaDB

 

 

 

1. MAVEN 프로젝트 생성

Intellij에서 Maven 프로젝트를 생성해 줍니다. (체크 : Maven, Project SDK = JDK9)

 

 

 

 

GroupId와 ArtifactId를 입력해줍니다. GroupId는 프로젝트를 그루핑해주는 ID이고 ArtifactId는 GroupId와 Version을 생략한 이 프로젝트의 이름이라고 보면 됩니다.(ArtifactId로 폴더이름 생성됨)

 

Next와 Finish를 눌러줍니다.

 

 

 

 

프로젝트가 만들어지면 오른쪽 아래에 "Enable Auto-Import"를 클릭합니다.

 

 

 

 

프로젝트 이름에서 오른쪽 마우스 -> "Add Framework Support..."를 클릭해줍니다.

 

 

 

왼쪽에서 Spring안에 "Spring MVC (5.2.3.RELEASE) 를 체크 해주고 OK를 눌러줍니다. (버전은 다를 수 있음)

그러면 프로젝트에 "web"폴더가 생기며 안에 servlet.xml등이 생깁니다.

 

 

 

 

2. RUN (Tomcat Server) 설정

우측 상단의 "ADD CONFIGURATION..."을 클릭하면 아래의 "Run/Debug Configurations"창이 뜹니다.

이후 왼쪽의 옥색 "+"를 클릭 -> "Tomcat Server"를 클릭 -> "Local"을 클릭합니다. (Tomcat이 Local에 있는경우)

 

 

 

 

오른쪽 아래의 "FIX"버튼을 눌러줍니다.

 

 

 

"Application context"가 "/backendspring_war_exploded"로  되어있는데 이거를 "/"로 replace해줍니다.

그리고 "OK"눌러줍니다.

 

 

 

 

2. Dependency 추가 (POM.xml)

 

아래의 dependency를 pom.xml의 <project> </project안에 </version>아래에 붙여넣어줍니다.

 

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    <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>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <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>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>
        
    <!-- lombok library -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
            <scope>provided</scope>
        </dependency>
  
    <!-- logging library -->
        <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>
        </dependency>
 
 
        <!-- databind for json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>
        <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.3</version>
        </dependency>
 
 
    <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
    
    <!-- mariadb jbdc -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.6.0</version>
        </dependency>
        
        
    <!-- for test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
      </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
        </plugins>
    </build>
cs

 

 

 

 

단축키(Ctrl + Alt + Shift + S)를 눌러서 Project Structure를 열어줍니다.

 

 

 

 

 

3. Log4j 설정 (src/main/resources/log4j.xml)

 

src/main/resources/log4j.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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
    <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: %c - %m%n" />
        </layout>
    </appender>
 
    <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="info" />
        <appender-ref ref="console" />
    </root>
 
</log4j:configuration>
cs

 

 

 

 

 

4. MariaDB 세팅 설정 (resource/application.properties)

a. DB를 연결하기 위해서 resource폴더 내에 application.properties파일을 생성

<dbip>, <dbport>, <db>, username, password는 알맞게 수정

1
2
3
4
5
spring.database.class=org.mariadb.jdbc.Driver
spring.database.host=jdbc:mariadb://<dbip>:<dbport>/<db>?useUnicode=true&characterEncoding=utf8
spring.database.username=username
spring.database.password=password
 
cs

 

 

 

b. mapping할 db model 생성 (java.com.model/<db이름>.java)

(연결할 db의 필드에 따라 다름)

 

 

 

c. dao 생성 (java.com.dao/StocksRepository.java)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.khann.dao;
 
import com.khann.model.Stocks;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository
public class StocksRepository {
 
    private SqlSession sqlSession;
 
    @Autowired
    public StocksRepository(SqlSession sqlSession){
        this.sqlSession = sqlSession;
    }
 
    public Stocks findStocksByCompany(String company){
        return sqlSession.selectOne("database.getStocksByCompany",company);
    }
}
 
cs

 

 

 

 

d. mybatis의 query문 추가(resource/database/query.xml)

(연결할 db에따라 필드명 db명 다름)

 

 

 

 

5. Controller 설정 (src/main/java/groupId/controller1 and 2)

groupid이름으로 패키지 생성

src/main/java 아래에 프로젝트 생성 시 입력했던 groupId로 패키지를 만들어줍니다.

 

만든 패키지 안에 controller1와 controller2패키지 2개를 만듭니다.

 

 

 

a. HomeController.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
package com.khann.controller1;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
@RequestMapping("/home")
public class HomeController {
 
    @GetMapping("/ap/test")
    public @ResponseBody String homeTest(){
        return "home";
    }
 
    @RequestMapping(value  = "/home", method = RequestMethod.GET)
    public String home(ModelMap modelmap) {
        modelmap.addAttribute("author","codingTest");
        return "home";
    }
}
cs

 

 

 

b. APIController.java

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.khann.controller2;
 
import com.khann.dao.StocksRepository;
import com.khann.model.Stocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
@RequestMapping("/api")
@RestController
public class APIController {
    private StocksRepository stocksRepository;
 
    @Autowired
    public APIController(StocksRepository stocksRepository){
        this.stocksRepository = stocksRepository;
    }
 
    @RequestMapping(value = "/rest", method = RequestMethod.GET,produces = "application/json; charset=UTF-8")
    public Stocks restAPITest(@RequestParam("company"String company){
        return stocksRepository.findStocksByCompany(company);
    }
}
 
cs

 

 

 

 

 

 

 

 

 

6. web.xml and servlet.xml 설정 (web/WEB-INF/)

a. applicationContext.xml 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<mvc:annotation-driven/>
    <context:property-placeholder location="classpath:application.properties" />
    <context:component-scan base-package="com.khann"/>
    <!-- MariaDB JDBC DataSource -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${spring.database.class}" />
        <property name="url" value="${spring.database.host}" />
        <property name="username" value="${spring.database.username}" />
        <property name="password" value="${spring.database.password}" />
    </bean>
 
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:database/**" />
    </bean>
 
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory" />
    </bean>
cs

 

 

 

 

 

b. dispatcher-servlet.xml 

 

1
2
3
4
5
6
7
8
9
10
11
<mvc:annotation-driven />
    <context:component-scan base-package="com.khann.controller1"/>
    <!-- Process annotations on registered beans like @Autowired... -->
    <context:annotation-config/>
    <!-- This tag allows for mapping the DispatcherServlet to "/" -->
    <mvc:default-servlet-handler />
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
cs

 

 

 

 

c. rest-servlet.xml 

(파일 생성후 작성)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
    <!-- This tag registers the DefaultAnnotationHandlerMapping and
         AnnotationMethodHandlerAdapter beans that are required for Spring MVC  -->
    <mvc:annotation-driven />
    <!-- This tag allows for mapping the DispatcherServlet to "/" -->
    <mvc:default-servlet-handler />
 
    <!-- Process annotations on registered beans like @Autowired... -->
    <context:annotation-config/>
    <!-- 컴포넌트 스캔 -->
    <context:component-scan base-package="com.khann.controller2" />
 
</beans>
cs

 

 

 

 

d. web.xml 

<lister>태그 아래 부분을 드러내고 아래 내용을 붙여넣기

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
<!-- rest dispatcher config -->
    <servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/rest-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>rest</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <!-- dispatcher config -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/home/*</url-pattern>
    </servlet-mapping>
 
    <!-- encoding 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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
cs

 

 

 

 

7. views 설정 (web/WEB-INF/views)

views폴더 생성 후 진행

 

 

a.home.jsp

1
2
3
4
5
6
7
8
9
10
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${author}</h1>
    Hello Spring MVC!!
</body>
</html>
cs

 

 

 

 

 

실행 및 체크

오른쪽위에 아까 설정한 tomcat으로 되어있는지 확인 후 화살표 클릭

 

 

웹 체크 

 

API 체크

반응형

이 글을 공유합시다

facebook twitter googleplus kakaostory naver