Post

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

스프링 웹 개발 기초




정적 컨텐츠


html 파일을 그대로 웹 브라우저에 내려주는 것을 말합니다. 기본적으로 스프링은 static 폴더 아래에 있는 html 파일을 정적 컨텐츠로 보여줍니다.

웹 브라우저에서 hello-static.html 입력이 들어오면, 내장 톰캣 브라우저가 받고, 스프링에서는 먼저 컨트롤러가 있는지 확인합니다. (컨트롤러에 우선순위가 있습니다.) 컨트롤러에 없으면 resources/static 안에서 찾아서 반환해주게 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// resources/static/hello-static.html
<!doctype html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport"  
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">  
    <meta http-equiv="X-UA-Compatible" content="ie=edge">  
    <title>hello-static</title>  
</head>  
<body>  
<div> 정적 컨텐츠 테스트 </div>  
</body>  
</html>




MVC와 템플릿 엔진


MVC는 Model View Controller 로 나누어지는 디자인 패턴으로, 비즈니스 로직과 화면을 구분하는 것에 중점을 두고 있습니다. 쉽게 말해서 View는 화면에 관련된 것만, Controller는 비즈니스 로직과 서버에 관련된 일만 작업하고 Model에 담아서 화면에 넘겨주는 방법이라고 볼 수 있습니다.

1
2
3
4
5
6
7
8
9
@Controller  
public class HelloConroller {
	// mvc와 템플릿 엔진 사용, html을 동적으로 변경시켜서 뿌려줌  
	@GetMapping("hello-mvc")  
	public String helloMvc(@RequestParam("name") String name, Model model){  
	    model.addAttribute("name", name);  
	    return "hello-template";  
	}
}
1
2
3
4
5
<html xmlns:th="http://www.thymeleaf.org">  
<body>  
<p th:text="'hello ' + ${name}">hello! empty</p>  
</body>  
</html>

localhost:8080/hello-mvc?name=spring을 브라우저에 입력하게 되면, 내장 톰켓 서버를 거치고 스프링에서 Controller에 hello-mvc가 있기 때문에 메서드를 호출합니다. 이 때 return을 hello-template로 했고, 모델을 (name: spring)으로 넘겨줍니다. ViewResolver가 return값과 똑같은 templates/hello-template.html을 찾아서 Thymeleaf 템플릿 엔진이 변환한 html을 웹브라우저에 반환해줍니다.




API


JSON 형식으로 데이터를 전달하는 방식입니다. @ResponseBody를 사용하면 http의 body에 문자 내용을 직접 반환합니다.

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
@Controller  
public class HelloConroller {    
    // API 방식 - 문자를 그대로 보내줌  
    @GetMapping("hello-string")  
    @ResponseBody // http의 body에 데이터를 직접 넣어주겠다는 표시  
    public String helloString(@RequestParam("name") String name) {  
        return "hello " + name;  
    }  
  
    // API 방식 - 객체를 return하면 json 형식으로 전달  
    @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() {  
            return name;  
        }  
  
        public void setName(String name) {  
            this.name = name;  
        }  
    }  
}

두개의 @ResponseBody 함수를 호출해보면 hello-string은 문자 그대로 http body에 반환해서 html 코드 없이 반환된 문자만 있는걸 볼 수 있습니다. hello-api는 {name: “spring”}으로 JSON 형태로 http body에 직접 반환됩니다.

@ResponseBody

  • http의 body에 문자 내용 직접 반환
  • viewResolver 대신에 httpMessageConverter가 동작
  • 문자열일 때 기본적으로 StringConverter 동작
  • 객체일 때 기본적으로 JsonConverter 동작