웹개발/Spring 로드맵

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

supremo7 2021. 2. 25. 02:39

<정적 컨텐츠>

- 웹 개발은 크게 세 가지 방법으로 하며, 정적 컨텐츠, MVC와 템플릿 엔진, API가 있습니다.

 

- static/ 에 있는 html파일은 정적 컨텐츠가 그대로 반환이 됩니다.

 

컨트롤러에서 먼저 찾고 static에서 찾습니다

<MVC와 템플릿 엔진>

- MVC는 Model, View, Controller입니다. 옛날에는 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";
 	}
}

//http://localhost:8080/hello-mvc?name=spring!와 같이 입력하여 인자전달함

 

"View"

<html xmlns:th="http://www.thymeleaf.org">
  <body>
  	<!-- 그냥 html로 볼때는 태그 사이의 내용이 보이고, 템블릿문법이 적용되면 치환됩니다.-->
  	<p th:text="'hello ' + ${name}">hello! empty</p>
  </body>
</html>

 

<API>

@ResponseBody 문자 반환

@GetMapping("hello-string")
@ResponseBody // response의 body부분에 직접 넣어주겠다는 의미
public String helloString(@RequestParam("name") String name){
  return "hello " + name;
}

 

- @ResponseBody를 사용하면, ViewResolver를 사용하지 않습니다. 대신, HTTP의 BODY에 문자 내용을 직접 반환합니다.(HTML 태그들이 하나도 없이)

 

@ResponseBody 객체 반환

@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를 사용하고, 객체를 반환하면 객체가 JSON으로 변환됩니다. (옛날에 XML많이 쓰다가 요즘은 JSON으로 거의 통일됐습니다)