━━━━ ◇ ━━━━
Spring/Spring 실무

Spring + Maven 연동하기

10개월 간의 교육을 마치고 다이렉트로 취업에 성공하였다.


내가 취업한 회사는 부산 센텀시티에 위치한 솔루션 회사다.


입사한 다음 처음으로 받은 미션은 


Spring 과 Maven 을 연동하여 Hello World 찍기 


이다.


https://maven.apache.org/ 에 접속하여 maven을 다운 받았다.



굳이 사진까지 첨부하여 설명을 하자면, 다운로드 카테고리에서 Binary zip archive 파일을 다운 받아 적당한 위치에 압축을 풀어 주었다.


그런 다음 Eclipse를 실행시켜 메이븐을 연동 시켰다.


구체적인 방법은 Eclipse 에서 (참고로 나는 STS를 사용했다) 설정 파일을 연다.


좌측의 메뉴에서 Maven 을 찾아 확장시켜보면 Installations 가 있다.


Add 버튼을 눌러 설치된 메이븐 폴더를 지정해 준다.



그런 다음 User Settings 메뉴를 눌러서 setting 파일을 연결한다.


이 설정은 하지 않아도 상관없지만 나처럼 로컬 저장소를 임의로 변경하고 싶으면 해야한다.


세팅 파일을 연결하면 로컬 저장소가 자동으로 입력된다.


로컬 저장소를 변경하는 방법은 사용자가 직접 세팅파일을 열어서 수정해야 한다.



세팅 파일의 위치는 메이븐 폴더의 conf 폴더를 열어보면 있다.


세팅 파일을 편집 프로그램으로 열어 로컬 저장소를 설정해줬다.


로컬 저장소의 디폴트 값은 C 드라이버 : \사용자 \.m2 폴더 이다.



이제 기본 설정이 끝이 났다.



위 캡쳐와 같이 Spring Legacy Project 를 새로 만들어 준다.



프로젝트 이름을 입력하고, Spring MVC Project 를 선택한 다음 Next 를 클릭한다.


참고로 처음 프로젝트를 생성한다면, 자동으로 다운로드가 실행될 것이다.


기다려 주면 된다.


다운로드된 파일은 위에서 설정한 로컬 저장소에 저장된다.



디폴트 패키지 이름을 입력하고 Finish를 클릭한다.



대충 위와 같은 구조의 프로젝트가 생성 되었다.



가장 먼저 pom.xml 파일을 열었다.


이곳에 각종 Dependency를 주입하면 자동으로 Maven Repository 에서 라이브러리를 다운 받을 수 있다.


Dependency는 https://mvnrepository.com/ <== 여기에서 검색하여 주입하면 된다.



검색어를 입력하고 검색을 하면 위 캡쳐 처럼 여러 결과가 나오는데 맞는 것을 찾아 클릭한다.



버전 선택이 중요한데, 무조건 최신 버전이 좋은것은 아닌것 같다. 


실제로 적용했을때 에러가 나는 경우가 잦았다.


그래서 나는 위 캡쳐처럼 하얀색으로 표시되어 있으며,


Usages를 보고 많은 사용자가 사용한 검증된 버전을 사용한다.



이제 위에 표시된 부분의 내용을 복사한다.


참고로 Gradle도 이곳에서 찾아서 사용할 수 있다.



pom.xml에 붙여주면 된다.


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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.imex.Test;
 
import java.util.Locale;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
/**
 * Handles requests for the application home page.
 *
 * Controller annotation: Controller로 사용하고자 하는 클래스에 @Controller 어노테이션을 명시하여 사용합니다.
 * servlet-context.xml에 있는 context:component-scan 에 등록되어 요청에 따라 호출됩니다.
 */
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /*
     * RequestMapping은 Controller의 메서드와 URL을 맵핑할 때 사용한다.
     * value: 디폴트 속성이기 때문에, 밸류만 정의한다면 앞 부분은 생략하고 URL만 입력 가능하다.
     * method: GET, POST 등 HTTP Request method에 따라 타입을 지정할 수 있다.
     * params: HTTP Request로 들어오는 파라미터 표현이다. */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        return "home";
    }
    /*
     * 27~32 라인을 설명하자면,
     * URL 주소 "/" 가 호출되었을때, home()메소드가 호출된다.
     * home()메소드는 파라미터로 locale을 가지고 있으며, 29번 명령문에 의해 콘솔에 로그가 출력된다.
     * 그리고 31번 명령문에 의해 String 타입의 home2가 리턴된다.
     * HomeController2가 종료되면 Front Controller에 의해 적절한 View를 호출하게 된다.
     * -->servlet-context.xml 의 InternalResourceViewResolver구문을 보면
     * 홈컨트롤러에서 리턴된 값의 앞에 /WEB-INF/views/가 붙고, 뒤에 .jsp가 붙는 View를 맵핑하게된다.
     * 결론적으로 /WEB-INF/views/home2.jsp 가 호출되어 사용자에게 보여진다.
     * */ 
    
}
 
cs



home.jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring Maven Test</title>
</head>
<body>
    <h1>Spring Maven Test</h1>
    <p>Hello World ~~~!!!</p>
</body>
</html>
cs



과장님에게 보고하기 위해 주석을 엄청 자세하게 달아놓아 더이상의 자세한 설명은 생략한다.


위 와 같이 깔끔하게 성공 !!!


두번째 과제는 Gradle로 빌드하는 것이었다. 


Gradle로 빌드하는 것은 다음 글에...

'Spring > Spring 실무' 카테고리의 다른 글

Spring + Gradle 연동하기  (0) 2017.01.03
COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 08. 모델 2 방식과 스프링 MVC

최근 모든 웹 개발은 거의 모델 2 방식을 사용한다고 해도 과언이 아니라고 합니다.


모델 2 방식은 MVC 구조를 응용한 방식으로, 화면과 데이터 처리를 분리해서 재사용이 가능하도록 하는 구조 라고 합니다.


좀 더 구체적으로, 컨트롤러가 모델 계층과 연동하여 필요한 데이터 처리를 하고, 그 결과를 뷰에 전송하는 구조 입니다.


모델(Model): 데이터 혹은 데이터를 처리하는 영역


뷰(View): 화면을 구성하는 영역


컨트롤러(Controller): 웹의 요청(Request)을 처리하는 영역


모델 2 방식의 장점은


1. 개발자와 웹 퍼블리셔의 영역을 분리할 수 있다.


2. 뷰의 교체나 변경과 같은 유지보수에 유용하다.


모델 2 방식의 한계


1. 각 컨트롤러 사이의 코드 중복


2. 개발자 간의 개발 패턴의 차이


모델 2 방식의 한계를 극복하고자 좀더 강제적인 형태인 Front Controller 방식이 등장합니다.


프런트 컨트롤러 패턴의 가장 중요한 변화는 전체 로직의 일부만을 컨트롤러가 처리하도록 변경 되었다는 점입니다.


위임(Delegation) 이라고 부르는데, 로직의 일부를 컨트롤러에게 위임하고, 


모든 흐름의 제어는 프런트 컨트롤러에서 담당하는 구조 입니다.


이 구조를 사용할 경우, 개발자가 작성해야할 코드는 전체 로직의 일부분으로 한정되기 때문에, 


각 개발자에게 할당되는 코드량이 줄어듭니다.


또, 모든 컨트롤러는 프론트 컨트롤러의 일부분을 구현하는 형태이므로, 좀 더 규격화된 코드를 작성하게 됩니다.


스프링 MVC의 경우는 다음과 같은 구조를 가집니다. 


1. Front Controller --> 2. Controller --> 3. service --> 4. DAO --> 5. Mybatis(Mapper) --> 6. MySQL


--> 7. MyBatis --> 8. DAO --> 9. service --> 10. Controller --> 11. Front Controller --> 12. View


간단한 테스트를 통해서 스프링 MVC 작업을 해보자


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.aristatait.spring;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class SampleController {
 
    private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
    
    @RequestMapping("doA")
    public void doA(){
        logger.info("doA called........................");
    }
    
    @RequestMapping("doB")
    public void doB(){
        logger.info("doB called..........................");
    }
}
 
cs


8번 라인을 보면 애노테이션으로 해당 파일이 Controller 역할을 한다는 것을 명시 한다.


이 컨트롤러에서는 doA 와 doB 라는 주소가 요청될때 로그가 출력되도록 로직이 구성되어 있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.aristatait.spring;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class SampleController2 {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleController2.class);
    
    @RequestMapping("doC")
    public String doC(@ModelAttribute("msg"String msg){
        
        LOGGER.info("doC called..........................");
        
        return "result";
    }
}
 
cs




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
package com.aristatait.spring;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.aristatait.domain.ProductVO;
 
@Controller
public class SampleController3 {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleController3.class);
    
    @RequestMapping("/doD")
    public String doC(Model model){
        
        LOGGER.info("doD called..........................");
        
        ProductVO product1 = new ProductVO("바나나"3000);
        
        LOGGER.info("doD");
        
        model.addAttribute(product1);
                
        return "productDetail";
    }
}
 
cs




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
package com.aristatait.spring;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
@Controller
public class SampleController4 {
 
    private static final Logger logger = LoggerFactory.getLogger(SampleController4.class);
 
    @RequestMapping("/doE")
    public String doE(RedirectAttributes rttr) {
        logger.info("doE called but redirect to /doF...........");
 
        rttr.addFlashAttribute("msg""This is the Message!! with redirected");
        return "redirect:/doF";
    }
 
    @RequestMapping("/doF")
    public void doF(String msg) {
        logger.info("doF called.................." + msg);
    }
}
 
cs




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.aristatait.spring;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.aristatait.domain.ProductVO;
 
 
@Controller
public class SampleController5 {
 
  @RequestMapping("/doJSON")
  public @ResponseBody ProductVO doJSON(){
    
    ProductVO vo = new ProductVO("샘플상품"30000);
    
    
    return vo;
  }
  
}
 
cs




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
package com.aristatait.spring;
 
import javax.inject.Inject;
 
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
 
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration( locations = {"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class SampleControllerJUnit {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleControllerJUnit.class);
    
    @Inject
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    
    @Before
    public void setup(){
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        LOGGER.info("setup.......................");
    }
    
    @Test
    public void testDoA() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/doC"));
    }
}
 
cs


COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 07. MyBatis 연결 설정하기

스프링을 이용한 개발 중 국내에서 가장 많이 사용되는 방법이

MyBatis와의 연동 작업을 통해서 SQL 처리에 대한 개발 생산성을 높이는 방법이라고 하더라.


쉽게 말해서 현업에서 많이 사용하는 방법이라고 하니


우리도 배워 보자.


우선 pom.xml 에 라이브러리를 추가해 볼거야.



프로젝트의 pom.xml 파일을 더블 클릭



에디터 윈도우 하단의 Dependencies 를 선택



add 선택



위의 라이브러리 들을 입력해 주면 되.



라이브러리를 추가하는 또 다른 방법은 에디터 윈도우 하단의 pom.xml 을 선택



dependencies 안에 수동으로 직접 입력해도 되


복사 붙여 넣기 하라고 소스를 올려주는 친절을 보여줄까?


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
<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
cs


위의 설정을 pom.xml에 추가하고 저장해서 라이브러리가 다운로드 되는 것을 확인할 수 있어.


이제 root-context.xml 를 수정해 보자.



이 파일은 스프링과 관련된 설정을 할 때, 웹 자원과 관련되지 않은 모든 자원의 설정을 위해 존재한대.


웹 자원의 경우에는 appServlet 을 열어보면 다른 xml 파일이 있을거야.



root-context.xml 파일을 더블클릭하고 에디터 윈도우 하단의 namespaces 를 선택



위의 체크된 부분을 선택해줘



다시 하단의 source 탭을 선택하면



네임스페이스 에서 체크한 것들이 소스에 자동으로 입력되어 있는 것을 볼 수 있을거야.


이제 MySQL 까지 연결해 보자.


root-context.xml 파일을 손봐야 한다는 것까진 이제 알겠지?


좀 전에 추가한 spring-jdbc 모듈의 클래스를 이용해서 DataSource 라는 것을 추가해 줘야 해.


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
<?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:aop="http://www.springframework.org/schema/aop"
    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.1.xsd
        http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        lazy-init="false">
 
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/springdb" />
        <property name="username" value="Spring" />
        <property name="password" value="1234" />
    </bean>        
</beans>
 
cs


이런식으로 작성하면 되


20번 라인에는 자기 아이피를 입력하면 될것이고


21번 라인에는 db 접속자 아이디


22번 라인에는 비밀번호


이제 DataSource 테스트를 진행 해 보자.



테스트를 위한 새 클래스를 생성하고



생성된 위치는 위와 같아


src/test/java에 생성했어


DataSourceTest.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
package com.aristatait.spring;
import java.sql.Connection;
 
import javax.inject.Inject;
import javax.sql.DataSource;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class DataSourceTest {
 
    @Inject
    private DataSource ds;
    
    @Test
    public void testConnection() throws Exception {
 
        try (Connection con = ds.getConnection()) {
            System.out.println(con);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}
cs




@ 뒤에 쓰여져 있는 코드들은 애노테이션이라고 불러


구체적으로 12번 13번 라인의 애노테이션은 현재 테스트 코드를 실행할 때 스프링이 로딩되도록 하는 부분이고


16번 라인은 인스턴스 변수를 스프링이 생성해서 주입해 주므로 개발자가 객체 생성 혹은 다른 작업을 하지 않아도 되도록 


만들어 줘.


그리고 19번 라인은 테스트를 진행하지


이제 테스트를 해보자


JUnit 으로 실행을 하면 되



테스트할 파일을 우클릭하고 Run As > Junit Test 를 선택하는 거야


그런데 그 결과가 기대했던 내용이 아니네 ㅠㅠ



콘솔에도 DB에 연결되었다는 문구가 없고



JUnit의 실행 결과에도 Errors 가 떴어



지난번 포스트에서 언급했었는데, 이걸 내가 빼먹었더라구


JUnit 의 버전은 4.11 이상이 되도록 해야 하는데 그대로 내버려 둬서


4.7로 되어 있었어



JUnit의 버전을 수정하고 다시 테스트를 실행 하였더니 


mysql에 정상적으로 연결되었음을 확인 할 수 있었어



JUnit의 실행 결과에도 아무런 에러가 검출되지 않았고


여기서 잠깐 정리하고 넘어가자


지금까지 했던 내용은 


1. pom.xml에 라이브러리 추가


2. root-context.xml 에 네임스페이스 설정 및 DataSource 연동

(MySQL - Spring 연결)


이제 할일은 Spring - MyBatis 연결 이야.


root-context.xml을 먼저 수정해야 겠지?



DataSource 밑에 sqlSessionFactory를 추가 했어


앞서 MyBatis 가 SQL 문의 처리를 도와주는 것이라고 했는데,


sqlSessionFactory 는 데이터베이스와의 연결과 SQL의 실행에 대한 모든 것을 가진 객체라고 하더라.


<property name="configLocation" value="classpath:/mybatis-config.xml"></property> 이부분은


SQL Mapping 프레임 워크를 별도의 파일로 만들어 주기 위해 삽입한 문구야


지금은 복잡해 보이지만 나중에 보기가 편해질꺼야


예전에 JSP 프로젝트를 해본적이 있는데, 그때 SQL Map 을 따로 분리해 놓으니까 


콘트롤러 파일에서는 아이디만 호출하고 SQL 문은 따로 정리가 되어 있더라구.



이렇게 하나 만들어 주고


그 소스 코드는 


1
2
3
4
5
6
7
<?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>
cs


여기에 각종 SQL 문이 추후에 추가된다는 거지


지금은 그냥 파일만 만들어 놓았어


초반에 설정하는 작업 이니까


이제 테스트를 해야지


MyBatisTest.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
package com.aristatait.spring;
 
import javax.inject.Inject;
 
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class MyBatisTest {
 
    @Inject
    private SqlSessionFactory sqlFactory;
    
    @Test
    public void testFactory() {
        System.out.println(sqlFactory);
    }
    @Test
    public void testSession() {
        try (SqlSession session = sqlFactory.openSession()){
            System.out.println(session);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}
 
cs




JUnit으로 테스트를 실행하면



연결 성공 !!!


이 포스트는 여기까지 


그럼 ㅂㅂ2






COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 06. 스프링 맛보기 2 Student


우선 새 프로젝트를 생성하자.


이번에도 Simple Spring Maven 을 선택 하면 되.


프로젝트가 생성되면 클래스 들이 있어야 겠지?



Main 클래스를 생성하고



학생 클래스도 생성해 줘야지.


지난 포스트와 마찬가지로 이 클래스는 이미 만들어져 있는 걸 받아왔다고 가정할게.


이렇게 가정하는 이유는 스프링이 기존의 클래스들을 어떻게 재활용 하는지 보여주기 위해서 인것 같아.


Student.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.aristatait.spring;
 
//기존에 있던 클래스라고 가정
public class Student {
    //멤버변수
    private String name;
    private String age;
    private String gradeNum;
    private String classNum;
    
    //생성자
    public Student(String name, String age, String gradeNum, String classNum) {
        super();
        this.name = name;
        this.age = age;
        this.gradeNum = gradeNum;
        this.classNum = classNum;
    }
 
    //Getter Setter
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAge() {
        return age;
    }
 
    public void setAge(String age) {
        this.age = age;
    }
 
    public String getGradeNum() {
        return gradeNum;
    }
 
    public void setGradeNum(String gradeNum) {
        this.gradeNum = gradeNum;
    }
 
    public String getClassNum() {
        return classNum;
    }
 
    public void setClassNum(String classNum) {
        this.classNum = classNum;
    }
    
    
    
    
    
}
 
cs



위의 Student.java 파일을 아래와 같이 재활용 해 봤어.


StudentInfo.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
package com.aristatait.spring;
 
//has a 관계로 클래스 생성
public class StudentInfo {
 
    private Student student; // <== 여기 중요 !!
    
    public StudentInfo(Student student) {
        super();
        this.student = student;
    }
 
    public void getStudentInfo(){
        if(student!=null){
            System.out.println("이름 : " + student.getName());
            System.out.println("나이 : " + student.getAge());
            System.out.println("학년 : " + student.getGradeNum());
            System.out.println("반 : " + student.getClassNum());
            System.out.println("==============================");
        }
    }
 
    public void setStudent(Student student) {
        this.student = student;
    }
    
    
}
 
cs




스프링에서 클래스를 재활용하는 방법은 자바와 달리 포함관계(Have a 관계 or Has a 관계)를 사용해.


StudentInfo.java 소스에서 6번 라인을 보면 Student 클래스 타입의 변수 student 가 선언되었어.


보통의 자바 프로그래밍에서 위와 같은 변수를 사용하기 위해서는 생성자 안에 


student = new Student(); 와 같은 문장이 필요 했을 거야.


하지만 스프링에서는 객체의 생성을 xml 리소스에 위임(?) 하기 때문에 위와 같은 문장이 필요가 없대.


8번 라인을 보면 StudentInfo 생성자의 매개변수로 Student 클래스가 사용되는걸 볼 수 있어.


이로 인해서 StudentInfo 클래스는 Student 클래스의 Properties 를 포함하는 클래스가 된것이지.


이제 좀 전에 말한 xml 리소스 파일을 만들자.



리소스 파일은 리소스 폴더에 만드는게 좋아.


적당히 이름을 만들어 주고 Finish !



리소스 파일을 열어서 하단의 Overview 탭을 선택하면 위와 같은 화면을 볼 수 있을 거야.


New Bean 버튼을 눌러서 



아이디와 클래스를 입력해 주면 되.


여기서 클래스는 Browse 를 클릭하여 검색을 하면 쉽게 입력 할 수 있어.



대충 느낌 오지??


이 방법으로 Student1, Student2, StudentInfo Bean을 생성하였어.


참고로 Student1 과 Student2 의 클래스는 둘다 Student 야.

 

하단의 Source 탭을 선택해 내용물(?)을 채워 주자.


applicationCTX.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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
 
    <bean id="student1" class="com.aristatait.spring.Student">
        <constructor-arg>
            <value>홍길동</value>
        </constructor-arg>
        <constructor-arg>
            <value>10살</value>
        </constructor-arg>
        <constructor-arg>
            <value>3학년</value>
        </constructor-arg>
        <constructor-arg>
            <value>2반</value>
        </constructor-arg>
    </bean>
    <bean id="student2" class="com.aristatait.spring.Student">
        <constructor-arg value="홍삼삼"/>
        <constructor-arg value="9살"/>
        <constructor-arg value="2학년"/>
        <constructor-arg value="1반"/>
    </bean>
    <bean id="studentInfo" class="com.aristatait.spring.StudentInfo">
        <constructor-arg>
            <ref bean="student1"/>
        </constructor-arg>
    </bean>
</beans>
 
cs




일부러 Student1 과 Student2의 내용물(?)을 채우는 방법을 달리 해봤어.


하지만 둘다 결과는 같아.


편한 방법을 사용하면 되.


그리고 StudentInfo 는 Student1 의 내용물을 ref(reference : 참고하다) 하고 있어.


아마도 StudentInfo 를 동작시키면 Student1 의 내용물(?)이 나올것 같지?


자 이제 파일을 실행해 볼게


Main 클래스에 코드를 작성해야 겠지?


MainClass.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.aristatait.spring;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
 
    public static void main(String[] args) {
        String configLocation = "classpath:applicationCTX.xml";
        AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
 
        StudentInfo studentInfo = ctx.getBean("studentInfo",StudentInfo.class);
        studentInfo.getStudentInfo();
        
        Student student2 = ctx.getBean("student2",Student.class);
        studentInfo.setStudent(student2);
        studentInfo.getStudentInfo();
        
        ctx.close();
    }
 
}
 
cs




이전 포스트와 동일하게 클래스패스를 잡아주고,


클래스패스에서 bean 들을 가져와서 객체를 생성해 줬어.


클래스 내부에 만들어져 있던 메소드를 호출해 보면...



짜잔 !!!


뭐 대충 이런것 이라고 하네...


이 포스트는 여기까지 그럼 ㅂㅂ2

COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 05. 스프링 맛보기 Calculator

Spring 맛보기를 위해서 Calculator 를 만들어 보자.



Simple Spring Maven 으로 새 프로젝트를 생성



Calculator 클래스 생성


이 클래스는 우리가 직접 작성하지만 


기존에 만들어져서 제공된 클래스라고 가정 하자.


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
package com.aristatait.spring;
 
public class Calculator { //기존에 제공하고 있는 클래스 라고 가정
 
    private int firstNum;
    private int secondNum;
    
    ////user custom method /////////////////////////
    public void add(int f, int s){
        System.out.println("add() 실행됨");
        System.out.println(f + " + " + s + " = " + (f+s));
    }
 
    
    ////Getter Setter /////////////////////////////
    public int getFirstNum() {
        return firstNum;
    }
 
    public void setFirstNum(int firstNum) {
        this.firstNum = firstNum;
    }
 
    public int getSecondNum() {
        return secondNum;
    }
 
    public void setSecondNum(int secondNum) {
        this.secondNum = secondNum;
    }
}
 
cs


우리는 이 Calculator 클래스를 가공하여 MyCalculator 클래스를 만들었다.


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
package com.aristatait.spring;
 
public class MyCalculator {
 
    private Calculator calculator;
    private int firstNum;
    private int secondNum;
    
    //////// User custom method //////////////////////
    public void add(){
        calculator.add(firstNum, secondNum);
    }
    
    //////// Getter Setter      //////////////////////
    public Calculator getCalculator() {
        return calculator;
    }
    public void setCalculator(Calculator calculator) {
        this.calculator = calculator;
    }
    public int getFirstNum() {
        return firstNum;
    }
    public void setFirstNum(int firstNum) {
        this.firstNum = firstNum;
    }
    public int getSecondNum() {
        return secondNum;
    }
    public void setSecondNum(int secondNum) {
        this.secondNum = secondNum;
    }
    ////////////////////////////////////////////////////
}
 
cs


이 클래스에서는 기존에 제공된 Calculator 의 메소드를 사용하는 메소드를 가지고 있다.



일단 메인 클래스도 만들어 놓고




위와 같이 리소스 폴더에 우클릭 -> new -> Spring Bean Configuration File 을 선택



만들어주면



위와 같이 xml 소스가 자동으로 입력된다.



오버뷰를 선택해서



뉴 빈을 선택한다.



id 를 입력하고 Browse 를 클릭하여



MyCalculator 클래스를 불러온다.



finish!



이런 방법으로 bean 을 만들 수 있다.


물론 직접 코딩해도 된다.




위와 같이 bean 을 입력한다.



이제 메인을 완성 하고, 실행해 보면 콘솔창에 계산 결과가 표시된다.


지금까지 한 내용이 뭐지 싶을꺼다.


우리가 자바에서 위와 같은 프로그램을 코딩했다면


객체를 생성하기 위해 new를 사용하였을 것이다.


하지만 스프링에서는 xml에 bean 을 등록하는 행위가 


객체를 생성하는 것을 대신한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="calculator" class="com.aristatait.spring.Calculator"></bean>
    
 
    <bean id="myCalculator"
        class="com.aristatait.spring.MyCalculator">
        <property name="calculator">
            <ref bean="calculator"/>
        </property>
        <property name="firstNum" value="10"></property>
        <property name="secondNum" value="2"></property>
    </bean>
</beans>
 
cs


위의 xml 에서 property 들은 각 클래스의 변수임을 알 수 있다.


1
2
3
4
String configLoc = "classpath:applicationCTX.xml";
        AbstractApplicationContext ctx 
                    = new GenericXmlApplicationContext(configLoc);
        MyCalculator myCalculator = ctx.getBean("myCalculator", MyCalculator.class);
cs


메인에서 이 xml 파일을 연결시켜주면 된다.

COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 04. MySQL 설정과 Spring 테스트

http://dev.mysql.com/downloads/installer/



여기서 인스톨러를 받아도 되고,


http://dev.mysql.com/downloads/mysql/




여기서 zip 파일을 받아도 된다.


자신의 취향껏 



나는 이미 설치가 되어 있기 때문에 위와 같은 창이 뜨네


add 를 눌러서 추가로 설치 해 보도록 할까?




이 비슷한 창이 뜰거야


MySQL Server 를 선택 해줘.



또 워크벤치도 설치해


나는 이미 설치가 다 되어 있어서 더이상 스샷을 못찍었어.


귀찮게 지웠다가 다시 깔 필욘 없는것 같아서 ㅋ


대충 말로나마 이 다음 진행을 설명해 주자면 


알아서 다운로드 받고 설치가 진행이 될거야.


그리고 설치가 완료되면 root 계정 비밀번호를 설정하는 부분이 나올꺼야


적당한 비밀번호를 설정해 주고 


next 를 하면 되


설치가 다 되면 workbench 를 실행해봐


워크벤치는 mysql 서버를 사용하는데 편의를 제공하는 툴이야.


eclipse 나 sts 처럼 프로그래머를 도와주는 프로그램이라고 생각하면 되



위와 같은 화면이 표시될건데,


아마 root 계정만 있을거야


일단 root 계정으로 들어가 보자.



이렇게 비밀번호 입력하라는 창이 뜰건데,


설치하면서 입력한 root 비밀번호를 입력하면 되


체크박스를 선택하면 다음부터 비밀번호를 안쳐도 되는데,


비밀번호를 저장해 놓으면 


혹시나 까먹을 수도 있으니까 그냥 매번 입력하는걸 권장해.



왼쪽 창에 표시된 부분(User and Privileges)을 선택해


그러면 가운데 표시된 창과 같은 부분이 뜰텐데


Add Account 를 눌러줘


아, 물론 root 계정으로 mysql 서버를 사용해도 상관은 없지만


가능하면 user 계정을 만들어서 사용하는 걸 좋다고 하더라고.



유저 아이디와 비밀번호를 설정 해줘



계정의 권한을 설정할 차례야 


나는 유저 어드민의 권한 만 줬어.


언제든지 수정가능한 부분 이니 알아서들 설정해



이제 접근할 수 있는 스키마를 부여해 줘야 해.


아참 스키마를 생성하는걸 깜빡했네


우선 왼쪽 창의 schemas 아래의 빈공간에 우클릭을 하면 위와 같은 메뉴가 생길꺼야


create schema 를 눌러




표시된 부분을 설정해줘


나는 springdb, utf-8을 설정했어



다시 유저 계정에서 스키마 접근 권한을 부여해 주자.


먼저 add entry 를 클릭 클릭 



모든 스키마를 설정해도 되지만, 난 springdb 스키마에만 접근 할 수 있게 했어




밑에 부분이 권한 인데,


그냥 셀렉트 올 했어 


그런 다음 apply 를 눌러주면 드디어 계정 설정이 끝이 났네



STS 로 돌아와서 pom.xml 를 열어봐



Dependencies 를 선택



Add 선택



그룹 아이디와 아티팩트 아이디 버전등을 입력해 주자.



이렇게 디펜던시가 추가 되었다.



MySQLTest.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.aristatait.spring;
 
import java.sql.Connection;
import java.sql.DriverManager;
 
import org.junit.Test;
 
public class MySQLTest {
 
    private final String DRIVER = "com.mysql.jdbc.Driver";
    private final String URL = "jdbc:mysql://127.0.0.1/springdb";
    private final String USER ="아이디";
    private final String PW = "비밀번호";
    
    @Test
    public void test() {
        
        try {
            Class.forName(DRIVER);
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try (Connection con = DriverManager.getConnection(URL, USER, PW)){
            System.out.println(con);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }
 
}
 
cs


MySQL Server 에 연결하는 코드를 입력하고


JUnit 으로 테스트를 진행


테스트할 파일을 우클릭 -> Run As -> JUnit Test 선택



콘솔창에서 mysql 서버에 연결된 것을 확인 할 수 있다.


JUnit 을 사용할때 에러가 발생하는 경우가 종종 있더라.


그런 사람들은 pom.xml 에서 JUnit 의 버전을 확인 하길 바란다.



나도 4.7로 되어 있는데 4.11 이상의 버전으로 수정해 주는 것을 권장한다.


여기서 에러가 발생하지 않더라도 나중에 MyBatis 쓸때 에러가 생기더라.


지금 최신 버전이 4.12 인가 그럴거다


오늘은 여기 까지 ㅂㅂ2


COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 03. Tomcat 8 설치 및 사용

http://tomcat.apache.org/download-80.cgi#8.0.37



톰캣 사이트에서 자신의 os에 맞는 버전을 다운로드 받아 주자.


service installer 로 프로그램을 설치하면 컴퓨터가 켜질때 자동으로 서버가 시작된다고 하네.


그러면 시스템 리소스를 항상 사용하기 때문에 난 zip 파일을 받아서 설치를 했어.



STS 에서 windows -> preferences -> server -> runtime environments 를 선택하면 위와 같은 화면이 나와.


나는 이미 톰캣이 등록되어 있지만 없는 사람들은 add 를 눌러



Tomcat 8 을 선택하고 next 를 클릭합니다.



browse 를 눌러서 설치된 아파치 폴더를 선택해 줘. 



new -> server 를 통해 서버를 만들어 두자.



여기서도 위의 방법과 마찬가지로 tomcat 8 을 선택하고 



이용 가능한 프로젝트를 애드 올 시켜 주면 끝! 


정상적으로 설치가 완료되었다면 



이렇게 서버 프로젝트가 생성되었을 거야.



프로젝트를 우클릭 해서, Run As > Run on Server 를 클릭하면



콘솔 을 보면 서버가 시작되었음을 확인 할 수 있지.


COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 02. STS 새 프로젝트 만들기

STS 를 시작하면 아래와 같은 화면이 떠! 


왠지 익숙하다고?


Eclipse 를 기반으로 만들어진 프로그램이라 아마도 익숙할거야.



우선 New -> Spring Project 를 선택해 줘.


Starter Project 는 초보자를 위해서 보다 많은 것을 자동으로 만들어 준다고 해.


나는 분명 초보자 이지만, 강사님은 초보자가 아니기에 Legacy Project 로 새 프로젝트를 만들었어.



위와 같은 창이 새로 생길텐데, Project name 에 적당한 이름을 써.


그 다음 Templates 에서 Spring MVC Project 를 선택해.


처음 MVC Project 를 생성하면 자동으로 다운로드한 다음 Build 를 할거야. 잠시 기다려줘야 해.


우선은 Next 를 눌러줘.



여기에는 패키지를 작성하는 공간이야. 자바에선 패키지란을 비워두면 Defalut 패키지가 생성되었는데, STS 에서는 공란으로 둘수가 없는것 같아 Finish 버튼이 활성화가 안되더라구.


적당한 패키지 명을 입력한 다음 Finish를 누르면 프로젝트 생성 완료.


아까전에 언급했듯이 처음 생성할땐 다운로드가 진행되니까 차분히 기다려.



생성된 프로젝트를 보면 처음부터 뭔가 많이 만들어져 있어.


여기서 우리가 앞으로 자주 사용하게 될 부분을 빨간색 박스로 표시해 뒀어.


자주 쓰다보면 익숙해 지겠지.



우선 pom.xml 를 열어 볼게



이 화면이 표시 될 텐데 properties 에 자바 버전과 spring 버전을 수정해 줘야해.


이부분도 자동으로 설정이 되면 좋을텐데 아직은 몰라.


매번 프로젝트를 새로 생성할때 마다 바꿔줘야 할 것 같아.


자바 버전을 1.8로,


스프링 버전을 4.1.7로 바꿔주면 되.


바꿔 줄게 하나 더 있는데, 프로젝트 폴더를 우클릭해서 property 로 들어가면 아래와 유사한 창이 뜰꺼야.



왼쪽에서 Project Facets 를 선택한 다음 Java 버전을 1.8로 바꿔 줘야 해.



다시 home.jsp 화면을 열어봤어.


이 부분이 이 프로젝트의 첫화면이야. 대충 코드를 보면, Hello world! 라는 문구와 지금 시간이 표시되는 것 같아.



프로젝트를 실행시켜 보면 위와 같이 home.jsp 페이지가 열리는 걸 확인 할 수 있어.


오늘은 여기까지 그럼 ㅂㅂ2

COMMENT
━━━━ ◇ ━━━━
Spring/Spring 수업

Spring 01. 설치

어제 부터 Spring 수업에 들어갔어.


아직 잘은 모르겠지만, 예전에 JSP 수업 중에 배웠던 MVC 모델2 가 Spring이랑 깊은 연관이 있는것 같아.


어쨌든, 우선 수업들은 내용을 필기하는 마음으로 포스트를 시작하겠어.


우선 Spring 개발을 위한 툴들을 설치해야 겠지?


1. STS 설치


https://spring.io/ 에 접속 한다. 페이지를 스크롤 다운 하다보면 아래와 같은 화면을 볼 수 있을거야.



우리가 주목해야 하는 부분은 바로 'Spring Tool Suite' !!!


learn more about STS > 를 클릭하길 바래. 그러면 아래와 같은 화면을 볼 수 있을거야.


DOWNLOAD STS 가 보일 꺼야.


하지만 우리는 최신버전을 받지 않을꺼야. 


왜냐하면 최신버전이 마냥 좋은 것은 아니래. 


누가? 우리 강사님이...


왜 그런진 모르겠지만, 일단 이전 버전 중 최적화가 되어 있는 버전이 있는 것 같아.


그걸 다운 받을 것이기 때문에 아래 화면에 표시되어 있는 부분을 클릭하길 바래.


 

나는 분명 See All Versions 를 클릭했는데, STS 3.8.1.RELEASE 버전이 한번 더 내 눈앞에 나타났어.


코딩을 배우는 입장에서 이 홈페이지는 문제가 있어보여.


안그래?


아무튼 한번 더 클릭하는 수고를 끼치게 되었군. 난 화면 편집을 한번 더 하는 수고를 가졌고...

 




드디어 우리가 바라던 화면이 나왔어.


내가 다운 받은 버전은 3.7.3 버전이야. 자신의 컴퓨터 OS에 맞는 버전을 다운 받길 바래.


다운 받아서 압축을 풀면 1개의 폴더가 생길꺼야. 그 폴더를 열어보면 다시 3개의 폴더가 있을 꺼야.



이 중 sts-3.7.3 폴더를 열어보면...




STS.exe 파일이 보일텐데 


이것이 바로 Spring Tool Suite 를 실행시키는 파일 이야.


이제 설치는 끝났네.


다음 포스트에선 STS 툴로 새 프로젝트를 만들어 볼게. ㅂㅂ2


COMMENT
1 2 3 4 5 ··· 9