Spring - 스프링 웹 개발 기초(2)

1 분 소요

스프링 웹 개발 기초

정적 컨텐츠

정적폴더에 원하는 파일을 넣으면 그대로 반환함.

src > main > resources > static > hello-static-html

<!DOCTYPE HTML>
<html>
<head>
    <title>static content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
  • 동작 원리

image

실행 화면

image

MVC와 템플릿 엔진

MVC: Model, View, Controller

image-20px

위의 그림처럼 사용자가 controller를 조작하면 controller는 model을 통해서 데이터를 가져오고 그 정보를 바탕으로 시각적인 표현을 담당하는 view를 제어해서 사용자에게 전달되는패턴이다.

  • 서로 분리되어 각자의 역할에 집중해서 개발을 해서, 유지보수성, 애플리케이션의 확장성과 유연성이 증가하고 중복코딩이라는 문제점이 사라질 수 있다.
public class HelloController {

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

hello-template.html

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

실행 화면

image

@RequestParam(value = "name") 에서 디폴트 값은

(@RequestParam(value = "name", required = true) 이므로 name 값이 입력이 되어야 하므로 get 방식으로 parm으로 name 값을 넣어준 후 실행화면

image

API

	@GetMapping("hello-string")
    @ResponseBody // http body에 name 을 직접 입력하겠다
    public String helloString(@RequestParam("name") String name) {
        return "hello" + name;
    }

실행화면

image

	@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;

        public String getName() { // getter setter 단축키 alt + insert
            return name;
        }

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

실행화면

image

@ResponseBody 사용원리

image

  • @ResponseBody 를 사용
    • HTTP의 BODY에 문자 내용을 직접 반환
    • viewResolver 대신에 HttpMessageConverter 가 동작
    • 기본 문자처리: StringHttpMessageConverter
    • 기본 객체처리: MappingJackson2HttpMessageConverter -> 객체를 json으로 바꿔주는 라이브러리
    • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

참고자료

인프런 - 스프링 입문 (김영한)

카테고리:

업데이트:

댓글남기기