웹 개발 방식
파일을 그대로 web browser에 내려주는 방식
가장 많이 사용하는 방식으로 server에서 HTML을 변형해 view로 내려주는 방식
JSON 이라는 데이터 포맷으로 client에게 데이터 전달
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>
localhost:8080/hello-static.html
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
RequestParam의 required 기본값이 true이므로 웹브라우저에서 열 때 name이 존재해야함
=> localhost:8080/hello-mvc?name=spring!
이 때 ?는 HTTP get 방식
ㄴ required=false로 설정하면 name 없어도 됨
helloController
에 hello-mvc에 mapping 되어있음vierResolver
가 view를 찾아주고 template engine 연결*thymeleaf template의 장점은 html 파일을 작성한 후 server 없이 바로 열 수 있음. template engine으로 동작하지 않을 경우
사이의 문자 출력되고, template engine으로 동작하면 th:text에 해당하는 문자로 치환.<p th:text="'hello '+ ${name}">hello empty</p>
-java/hello.hellospring/controller/HelloController에 코드 추가
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
localhost:8080/hello-string?name=spring!
@ResponseBody는 HTML body가 아니라 HTTP의 body부를 직접 넣을 것을 의미
MVC와 다른 점은 hello + (name) 문자가 client로 view 없이 그대로 내려간다는 것
1) MVC
2) API
-java/hello.hellospring/controller/HelloController에 코드 추가
@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;
}
}
localhost:8080/hello-api?name=spring!
위 사진은 JSON 방식: key-value로 이루어진 구조
helloController
에서 hello-api 찾음HttpMessageConverter
가 동작static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
*위코드사용 alt+insert => getter, setter 생성
getter와 setter는 Javabean 표준 방식(=property 접근방식)
name은 private이라 외부에서 바로 못 꺼냄. 라이브러리에서 쓰거나 사용할 때 getName, setName 등의 메소드를 이용해 사용
*@ResponseBody사용
-HTTP의 BODY에 문자내용 직접 반환
-viewResolver 대신 HttpMessageConverter 동작
-기본문자처리: StringHttpMessageConverter(JSON형식으로 바꿔줌)
-기본객체처리: MappingJackson2HttpMessageConverter(JSON형식으로 바꿔줌)
-byte 처리 등 여러 HttpMessageConverter가 기본으로 존재
*참고
client의 HTTP Accept 해더와 서버의 컨트롤러 반환 타입 정보를 조합해서 HttpMessageConverter가 선택되지만, 요즘은 거의 JSON