Framework/Spring

[Spring] MVC 패턴

IT수정 2024. 10. 30. 10:45

정적 콘텐츠 만들기

다음 경로에 정적 콘텐츠를 만들어 보자.

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<a href="/hello-static.html">정적컨텐츠</a>
</body>
</html>

 

hello-static.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello-static</title>
</head>
<body>
<a href="/">Home으로 이동합니다.</a>
<p>정적 컨텐츠 입니다.</p>
</body>
</html>

 

localhost

index.html의 [정적콘텐츠] 링크를 클릭하면 hello-static.html로 이동하게 된다.

다시 [Home으로 이동합니다] 링크를 클릭하면 index.html로 돌아가게 된다.

 

정적 콘텐츠 구조

 

MVC

Model-View-Controller의 약자로, 소프트웨어 디자인 패턴이다. 주로 웹 애플리케이션과 GUI 애플리케이션에서 사용되며, 애플리케이션의 구조를 세 가지 주요 구성 요소로 나눈다. MVC 패턴을 이용해 웹 개발을 하면 클라이언트가 서버에 웹 문서를 요청할 때 HTML을 동적으로 바꾸어 응답해 준다.

 

Model

  • Model은 앱이 포함해야 할 데이터가 무엇인지 정의한다.
  • 리스트 항목이 포함해야 하는 데이터(ex 품목, 가격), 이미 존재하는 리스트 항목이 무엇인지를 지정한다.

View

  • 항목이 사용자에게 보이는 방식을 말한다.
  • 표시할 데이터는 모델로부터 받는다.

Controller

  • 앱의 사용자로부터의 입력에 대한 응답으로 모델 또는 뷰를 업데이트하는 로직을 포함한다.

 

동적 콘텐츠 만들기

MVC 패턴을 이용해서 다음 경로에 동적 콘텐츠를 만들어 보자.

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<a href="/hello">hello</a>
</body>
</html>

 

HelloController.java

package hellov2.hellov2_spring.controller;

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

@Controller
public class HelloController {

    @GetMapping("hello")
    // HTTP GET 요청을 처리할 경로를 지정, index.html의 /hello 경로를 의미
    public String hello(Model model) {
        model.addAttribute("data", "박수정");
        return "hello";
        // Thymeleaf 템플릿 엔진에 hello.html 파일을 렌더링하라는 의미
    }
}

 

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<p th:text="'반갑습니다, ' + ${data} + '님'">반갑습니다, 손님</p>
<!-- ${data} 값이 없으면, th:text 속성은 반갑습니다, 손님이라는 기본값을 출력하게 된다. -->
</body>
</html>

 

localhost

[hello] 링크를 누르면 내가 부여한 data의 값이 출력되는 것을 볼 수 있다.

 

사용자 입력값 받아보기

index.html

<a href="/hello-mvc">Param 데이터</a>

<!-- 파라미터 값이 정해지지 않은 경우 화이트라벨 에러 페이지가 뜨게 됨, 바로 연계하려면 다음처럼 주소부를 수정 -->
<a href="/hello-mvc?name=이름">Param 데이터</a>

 

HelloController.java

@GetMapping("/hello-mvc")
    public String helloMvc(@RequestParam("name") String name1, Model model) {
        // @RequestParam("name") : URL에서 전달된 파라미터 이름
        // name1 : 그 파라미터의 실제 값
        model.addAttribute("name", name1);
        // "name"이라는 키로 name1 값을 모델에 추가하여 뷰에서 사용할 수 있게 한다.
        return "hello-template";
    }

 

hello-template.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Template</title>
</head>
<body>
<p th:text="'hello! ' + ${name}">hello! empty</p>
</body>
</html>

 

localhost

URL에서 파라미터 값을 부여하면 이름이 바뀌는 것을 볼 수 있다.

 

MVC 패턴 구조

 

API 방식

Application Programming Interface의 약자로, 소프트웨어 애플리케이션 간의 상호작용을 위한 규칙과 프로토콜을 정의하는 것이다. API를 통해 서로 다른 시스템이나 애플리케이션이 데이터를 주고받고, 기능을 호출할 수 있다.

 

데이터를 그대로 넘겨보기

HelloController.java

 @GetMapping("hello-spring")
    @ResponseBody //컨트롤러 메서드의 반환 값을 HTTP 응답의 본문(body)으로 직접 사용하도록 지시
    public String helloSpring(@RequestParam("name") String name) {
        return "hello " + name;
    }

 

http://localhost:8080/hello-spring?name=name을 입력해 보면 보이는 것은 이전 예제와 동일하다.

하지만 소스 코드를 확인해보면 다른 점을 알 수 있다.

 

객체를 넘겨보기

Hello.java

package hellov2.hellov2_spring.domain;

public class Hello {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

HelloController.java

    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }

 

localhost

http://localhost:8080/hello-api?name=name을 입력해 보면 데이터가 JSON 형식으로 뜨는 것을 볼 수 있다.

 

Alt + Insert : Getter, Setter 자동 생성
Ctrl + Alt + V : 객체 자동 생성

 

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

[Spring] HTML 구성 요소의 통합  (2) 2024.10.31
[Spring] 회원 관리 예제  (1) 2024.10.31
[Spring] H2 서버 연결하기  (0) 2024.10.30
[Spring] IntelliJ IDEA 설정  (0) 2024.10.29
[Spring] 기본 환경 설정  (1) 2024.10.29