반응형

이번에는 MVC 패턴에 대해서 알아보겠습니다

 

MVC : Model, View, Controller 로써, 앞 글자를 따와서 MVC라는 단어가 생성이 되었습니다

Spring에서는 관심사를 분리하기 위해서 MVC패턴을 사용합니다.

 

그럼 코드를 직접 짜보겠습니다!


 

package helloo.helloo_spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @GetMapping("hello") // get 요청 처리
    public String hello(Model model) { // model 객체 매개변수, 문자열 반환
        model.addAttribute("data", "hello!");
        // model 객체에 data 속성 추가, 그 값을 hello! 설정
        return "hello"; // 뷰의 이름
        // 뷰 리졸버를 통해서 뷰 파일을 찾고 hello.html 반환
    }

    @GetMapping("hello-mvc") // 사용자가 hello-mvc URL을 접속하면 메서드 호출
    public String helloMvc(@RequestParam("name") String name, Model model) {
        // @RequestParam 어노테이션은 URL 쿼리 파라미터중 "name" 이라는 키를 가지고 오겠다 라는 의미
        model.addAttribute("name", name);
        return "hello-template";
    }
}

// @RequestParam 추가적 설명
// 사용자가 http://localhost:8080/hello-mvc?name="spring" 입력 후 접속시
// @RequestParam("name")에서 name을 찾아 추출 후 name 매개변수로 전달

 

helloMvc 메서드를 보시면 될거 같습니다.

 

hello-template.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

 


 

사용자가 http://localhost:8080/hello-mvc?name="spring" 을 입력후 접속하면

 

 

이렇게 뜨는걸 볼 수 있습니다

 


여기서 추가적인 작업을 해보도록 하겠습니다

- 사용자가 index를 입력하면 자동적으로 name 쿼리 파라미터를 전달함.

- 전달된 인자를 화면에 보여주는 페이지

 

1. 사용자가 입력할 수 있는 폼을 만들겠습니다

templates/input.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>폼 입력 페이지</title>
</head>
<body>
  <h1>이름을 입력하세요</h1>
  <form action="/hello-mvc-test" method="get">
    <label for="name">이름:</label>
    <input type="text" id="name" name="name" />
    <button type="submit">Submit</button>
  </form>
</body>
</html>

 

여기서 form action을 /hello-mvc-test로 했기 때문에 submit을 했을때 text에 적힌 name이 /hello-mvc-test로 전달됩니다.

 

 

2. input.html을 처리하기 위해서 Controller를 만들겠습니다

package helloo.helloo_spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @GetMapping("hello") // get 요청 처리
    public String hello(Model model) { // model 객체 매개변수, 문자열 반환
        model.addAttribute("data", "hello!");
        // model 객체에 data 속성 추가, 그 값을 hello! 설정
        return "hello"; // 뷰의 이름
        // 뷰 리졸버를 통해서 뷰 파일을 찾고 hello.html 반환
    }

    @GetMapping("hello-mvc") // 사용자가 hello-mvc URL을 접속하면 메서드 호출
    public String helloMvc(@RequestParam("name") String name, Model model) {
        // @RequestParam 어노테이션은 URL 쿼리 파라미터중 "name" 이라는 키를 가지고 오겠다 라는 의미
        model.addAttribute("name", name);
        return "hello-template";
    }

    // 여기부터
    @GetMapping("/")
    public String input() {
        return "input";
    }

    @GetMapping("hello-mvc-test")
    public String helloMvcTest(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template-test";
    }
    // 여기까지
}

// @RequestParam 추가적 설명
// 사용자가 http://localhost:8080/hello-mvc?name="spring" 입력 후 접속시
// @RequestParam("name")에서 name을 찾아 추출 후 name 매개변수로 전달

 

이미 static 폴더에 index.html이 있기때문에 GetMapping을 안해주면 static/index.html을 반환하기 때문에

GetMapping을 통해서 경로를 다시 설정해줍니다.

그리고 사용자가 입력 폼을 통해서 입력하고 제출했을때 보여주는 페이지 경로를 설정했습니다.

 

3. 결과값을 보여주는 페이지

templates/hello-template-test.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title>사용자가 입력한 값 출력</title>
</head>
<body>
  <h1>Hello, <span th:text="${name}">!</span></h1>
</body>
</html>

 

4. 결과

localhost:8080에 들어오게 되면

이런 페이지가 뜨고, 이름에 spring을 입력한 후 submit을 누르면

 

 

이런 화면이 뜨고 URL도 http://localhost:8080/hello-mvc-test?name=spring 
으로 변경된걸 확인 할 수 있습니다

 


 

실행과정

1. localhost:8080에 들어가게 되면 사용자가 입력할 수 있는 input.html을 보여줌

2. name을 입력하고 submit을 누르게 되면 name값이 hello-mvc-test로 전달된다.

그렇게 되면 http://localhost:8080/hello-mvc-test?name=입력된값 을 브라우저가 요청을 보냅니다.

3. hello-mvc-test 경로에 대한 요청을 처리하는 메서드를 호출한 후 요청 파라미터에서 name값을 모델에 추가한 후

4. hello-template-test.html 뷰가 렌더링된다.

 


위 글은 김영한님의 spring 입문 강의를 바탕으로 적었습니다!

반응형

'WEB > SPRING' 카테고리의 다른 글

Spring 자동 재시작  (0) 2024.07.25
Spring #4 정적 컨텐츠  (0) 2024.07.16
Spring #3 View 환경설정  (0) 2024.07.16
Spring #2 라이브러리 살펴보기!  (0) 2024.07.13
Spring #1 Spring 프로젝트 생성  (0) 2024.07.13

+ Recent posts