본문 바로가기

개발/Spring

[Spring Boot] Hello World 부터 Getter, Setter 불러오기 / ResponseBody

IntelliJ, Gradle, ThymeLeaf을 사용했다

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
package hello.hellopractice.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;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class HelloController {
 
    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data""I'm HyeseungChuu!!");
        return "hello"// hello.html을 찾는다
        // 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리한다.
    }
 
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam(name = "name"String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
 
    @GetMapping("hello-string")
    @ResponseBody       // http에서 (head/body) body부의 데이터를 내가 직접 넣어주겠다
    public String helloString(@RequestParam("name"String name) {
        return "hello " + name;
    }
 
    // 데이터를 내놔!
    @GetMapping("hello-api")
    @ResponseBody               // http 응답에 데이터를 넘겨야겠구나~ (객체 )
    public Hello helloApi(@RequestParam("name"String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }
 
    //  클래스 내에서 Hellocontroller.Hello로 활용할 수 있다(static)
    static class Hello {
        private String name;
 
        // Java bean 규약 = Property 접근 방식
        public String getName() {
            return name;
        }
 
        public void setName(String name) {
            this.name = name;
        }
    }
 
 
 
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" > 안녕하세요. 손님 </p>
</body>
</html>
cs

 

@ResponseBody 사용 원리