[Spring] 스프링 입문 Section 2 : 스프링 웹 개발 기초

z00m__in·2022년 5월 17일
0
post-thumbnail

스프링 웹 개발 기초

정적 컨텐츠

: static 아래에 존재하는 파일을 그대로 전달
https://docs.spring.io/spring-boot/docs/2.6.7/reference/htmlsingle/

MVC와 템플릿 엔진

: MVC(Model, View, Controller)는 서버가 일부 작동을 해서 전달

Controller

@Controller
public class HelloController {

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-template";
    }
}

View

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

API


@ResponseBody가 붙어있으면 http에 그대로 반환해야 한다는 것
-> 문자인 경우 그냥 그대로
-> 객체인 경우 Jason 방식으로 data를 만들어서 반환

@ResponseBody 문자 반환

@GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello" + name; // 뷰고 뭐고 그런 거 없고 이름 그대로 내려감
    }

@ResponseBody 객체 반환

@GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
        //Jason 방식으로 반환하는 게 기본
    }

    static class Hello{
        private String name;

        //Getter Setter 단축키는 Alt+Enter
        public String getName() {
            return name;
        }

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

본 포스트는 김영하의 <스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술> 강좌를 바탕으로 작성한 포스트입니다.

profile
우당탕탕 기록지

0개의 댓글