Backend/Spring Boot
원본 κΈ€ 보기

[Spring Boot] MVC νŒ¨ν„΄ 4: Controller, Model, View 예제

Spring Boot πŸƒ

μ§€λ‚œ ν¬μŠ€νŒ…μ—μ„œ Controller, Model, View 각각의 μ—­ν• κ³Ό 생성 방법을 μ•Œμ•„λ³΄μ•˜λ‹€.

μ΄λ²ˆμ—” 이 μ„Έκ°€μ§€λ₯Ό λ™μ‹œμ— μ‚¬μš©ν•˜μ—¬

μ‚¬μš©μžμ—κ²Œ μž…λ ₯ νŽ˜μ΄μ§€μ—μ„œ 두 μ •μˆ˜κ°’μ„ λ°›μ•„, 전솑 λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ 두 값을 λ”ν•œ 값을 좜λ ₯νŽ˜μ΄μ§€μ—μ„œ λ³΄μ—¬μ£ΌλŠ” κΈ°λŠ₯을 κ΅¬ν˜„ν•΄λ³΄λ„λ‘ ν•œλ‹€.

Controller



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

@Controller
@RequestMapping("/test")
public class TestController {

    @GetMapping("/input")
public String input() {
return "/test/input.html";
}

    @GetMapping("/result")
public String result(Model model, int num1, int num2) {
        model.addAttribute("result", num1 + num2);
return "/test/result.html";
}
}

μ‚¬μš©μžκ°€ μž…λ ₯ν•˜λŠ” νŽ˜μ΄μ§€λ₯Ό input λ©”μ†Œλ“œλ‘œ,

κ²°κ³Όλ₯Ό λ³΄μ—¬μ£ΌλŠ” νŽ˜μ΄μ§€λ₯Ό result λ©”μ†Œλ“œλ‘œ λ§Œλ“€μ–΄μ£Όκ³ ,

result λ©”μ†Œλ“œμ—μ„œ μ‚¬μš©μžκ°€ μž…λ ₯ν•œ int νƒ€μž…μ˜ num1κ³Ό num2λ₯Ό λ§€κ°œλ³€μˆ˜λ‘œ λ°›λŠ”λ‹€.

(λ§€κ°œλ³€μˆ˜λ‘œ λ°›λŠ” 방법은 λ§Žμ§€λ§Œ, 이에 λŒ€ν•œ μžμ„Έν•œ μ„€λͺ…은 λ‹€μŒμ— λ”°λ‘œ ν•˜κΈ°λ‘œ ν•œλ‹€.)

그리고 num1κ³Ό num2을 λ”ν•œ 값을 resultλΌλŠ” 이름(key)으둜 λͺ¨λΈμ— λ‹΄μ•„μ„œ ν΄λΌμ΄μ–ΈνŠΈμ—κ²Œ /test/result.htmlλ₯Ό λ°˜ν™˜ν•œλ‹€.

input.html



<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>input</title>
</head>
<body>
<form method="get" action="/test/result">
<input type="text" name="num1">
<input type="text" name="num2">
<input type="submit" value="전솑">
</form>
</body>
</html>

κ°„λ‹¨ν•˜κ²Œ num1, num2 값을 μž…λ ₯λ°›λŠ” text νƒ€μž…μ˜ input νƒœκ·Έμ™€

submit νƒ€μž…μ˜ λ²„νŠΌμ„ λ§Œλ“ λ‹€.

input νŽ˜μ΄μ§€

result.html



<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>result</title>
</head>
<body>
<h1 th:text="${result}"></h1>
</body>
</html>

input νŽ˜μ΄μ§€μ—μ„œ 전솑 λ²„νŠΌμ„ λˆ„λ₯΄λ©΄ ν˜ΈμΆœλ˜λŠ” result κ²°κ³Ό νŽ˜μ΄μ§€μ—λŠ”

νƒ€μž„λ¦¬ν”„ 문법을 μ‚¬μš©ν•΄μ„œ result 값을 화면에 λ„μš΄λ‹€.

ν”„λ‘œμ νŠΈλ₯Ό μ‹€ν–‰ν•΄λ³΄μž.

ν”„λ‘œμ νŠΈ μ‹€ν–‰ ν›„,

μ£Όμ†Œμ°½μ— input νŽ˜μ΄μ§€λ₯Ό μš”μ²­ν•΄μ„œ

input νŽ˜μ΄μ§€μ— 값을 μž…λ ₯ν•˜κ³  μ „μ†‘λ²„νŠΌμ„ λˆ„λ₯΄λ©΄

λ‹€μŒκ³Ό 같이 result νŽ˜μ΄μ§€μ— 3μ΄λΌλŠ” 값이 λ‚˜μ˜¨λ‹€.

μ•„λž˜ 그림으둜 이 과정을 μ •λ¦¬ν•΄λ³΄μž.