[스프링 입문] #02 스프링 웹 개발 기초

✨New Wisdom✨·2020년 12월 28일
1

📕 SpringBoot 📕

목록 보기
8/8
post-thumbnail

김영현님의 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 수강하면서 기록하는 노트 ✍️

정적 컨텐츠

스프링 부트는 정적 컨텐츠를 자동으로 지원해준다.

Example

static 파일 만들기 - hello-static


파일을 만들고 프로젝트를 실행 시킨다.

"http://localhost:8080/hello-static.html"


이렇게 패스에 파일명만 적어도 자동으로 반환이 된다!
하지만 정적 파일에는 어떤 프로그래밍을 할 수는 없다.
현 패스로 요청이 들어오면 스프링 부트는 먼저 controller에서 해당 파일을 찾고,
없다면 resources:statc/hello-static을 찾아 반환한다.

MVC와 템플릿 엔진

  • MVC : 모델, 뷰, 컨트롤러

Example

helloController

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

"hello-mvc"패스로 요청이 오면, "hello-template" 파일을 반환한다.
RequestParam으로 파라미터를 전달한다.
(@RequestParam(value = "name",required = true) 필수이며, name을 파라미터로 전달한다.

templates/hello-template

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'안녕하세요. ' +${name}">helo! empty</p>
</body>
</html>

"http://localhost:8080/hello-mvc?name=졔"

API

ResponseBody 객체의 반환

Example1

정적 컨텐츠를 제외하면 HTML로 내리냐, API로 데이터를 내리냐로 나뉜다.

@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name){
        return "hello " + name;
}

@ResponseBody의 활용

  • HTTP Body에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter가 동작
  • 기본 문자처리 : StringHttpMessageConverter
  • 기본 객체 처리 : MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

Example2

static class를 쓰면 class안에서 클래스 사용 가능.

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

    static class Hello{
        private String name;
		
        // getter와 setter은 java bean 표준 방식이다. (프로퍼티 접근 방식)
        public String getName() {
            return name;
        }

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


이렇게 json 형식으로 나온다!
객체가 오면 json으로 만들어 반환하는 것이 기본 정책!

profile
🚛 블로그 이사합니다 https://newwisdom.tistory.com/

0개의 댓글