스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 들으며 정리하는 POST입니다.
전체적인 흐름
- Spring Project 생성
- Spring boot로 웹 서버 실행
- 회원 도메인 개발
- 웹 MVC 개발
- DB 연동 - JDBC, JPA, Spring data JPA
- 테스트 케이스 작성
/static 폴더에서 정적 컨텐츠를 찾아서 제공한다./static 에 hello-static.html 을 생성 및 작성해보자.


html 파일을 확인할 수 있다.
정적 컨텐츠와 다른 점
서버에서 뿌려질 컨텐츠에 동적으로 변화를 줄 수 있다.
이번에는 MVC를 이용하여 Parameter를 받는 Controller를 생성해보자.
controller/HelloController.java
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam ("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
@RequestParam annotation은 HTTP request parameter를 method의 parameter로 전달받을 때 사용한다. form 에서의 input 의 name 과 매칭되어 해당 값을 받아올 수 있다.String name 에 해당 값을 담고, Model model 을 이용하여 View 에서 rendering 시 사용model.addAttribute method로 key 가 "name"이고, 변수이름 이 name 인 값을 가져와서 View 로 전달한다.resources/templates/hello-templates.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello' + ${name}">hello! empty</p>
</body>
</html>
xmlns:th="~" 로 thymeleaf 템플릿을 사용함을 명시th:text 에 있는 값으로 hello! empty 가 치환된다.서버를 동작시켜 http://localhost:8080/hello-mvc 로 접속

WARN 51004 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present]
name parameter에 아무것도 넘겨주지 않아서 뜨는 에러라고 할 수 있다.@GetMapping("hello-mvc")
public String helloMvc(@RequestParam (name = "name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
required option은 기본값이 true 이므로 그대로 둔다.이제 http://localhost:8080/hello-mvc?name=spring 으로 접속해보자.

public Stirng helloMvc 의 String name 에 담기고,model.addAttribute 를 통해 name 이 model 에 담겨, hello-template 으로 return${name} 으로, model 에서 key값이 name 인 값을 가져와서 치환!
JSON 이라는 데이터 포맷으로 서버에서 클라이언트로 데이터를 전송하는 방식@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello" + name;
}
@ResponseBody 는, http에서의 body에 해당 내용을 직접 넣겠다는 의미!페이지 소스 보기 하면, html code 없이 Data만 존재하는 것을 확인할 수 있다.

다음 예제는 Hello 객체와 getName & setName, 그리고 객체를 return 하는 Api 방식이다.
@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;
}
}
Key & Value 로 이루어진 JSON 구조를 확인할 수 있다.
mac 기준
⌘ + n으로 Getter와 Setter를 생성할 수 있다.
HelloClass 안에 있는String name은private이므로, 해당 변수에 대한 접근은 오직public한getNameorsetName으로만 가능하게 한다.
→ JavaBeans 표준 방식
@ResponseBody 를 사용한 동작방식은,@ResponseBody 를 발견하면 http 응답에 해당 Data를 그대로 전달하기 위한 처리를 수행HttpMessageConverter 가 동작하여StringConverter, 객체인 경우는 JsonConverter 를 동작시킴MappingJacksonHttpMessageConveter 와 GsonHttpMessageConveter 가 있다.예전에는 JSON이 아닌 XML 방식을 사용했었는데, (ex. html code)
이는 열고 닫는 이중의 code가 필요하고, 무겁다는 단점때문에
최근에는 Simple한 JSON 형태를 많이 사용한다.
Template engine, API, Annotation, HttpMessageConverter, JavaBeans