스프링 입문강의를 들으면서 복습겸 기록을 합니다.
정적 컨텐츠
( 그냥 파일을 그대로 웹 브라우저에 전달)
- 스프링 부트 정적 컨텐츠 기능
- https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features
// hello-static.html 파일 내용
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>static content</title>
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
- 실행 (http://localhost:8080/hello-static.html)
- 정적 컨텐츠 작동원리
MVC와 템플릿 엔진
( 서버에서 뭔가 변형해서 내려주는 방식 )
- MVC : Model, View, Controller
- 서로 담당하는 것들을 분리해서 관리를 한다.
<Controller> : 비지니스 로직과 관련, 내부를 처리하는것에 집중
@Controller
public class HelloController {
//원래 있던 것
@GetMapping("hello")
public String hello(Model model){
model.addAttribute("data", "hello!!");
return "hello";
}
//새로 생성한 것
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model){
model.addAttribute("name", name);
return "hello-template";
}
}
<View> : 보이는 것에 집중
resources/templates/hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello' + ${name}">hello! empty</p>
</body>
</html>
- 실행(http://localhost:8080/hello-mvc?name=spring?)
- MVC, 템플릿 엔진 작동원리
API
( json이라는 데이터 구조 포맷으로 클라이언트에게 전달 )
<@ResponseBody 문자 반환>
@Controller
public class HelloController {
//원래 있던 코드들 생략 ...
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name){
return "hello" + name;
}
}
- @ResponseBody를 사용하면 뷰 리졸버(viewResolver)를 사용하지 않음
- 대신에 HTTP의 BODY에 문자 내용을 직접 반환(HTML BODY TAG를 말하는 것이 아님, 문자내용만 보여짐)
- 실행 (http://localhost:8080/hello-string?name=spring)
<@ReponseBody 객체 변환>
@Controller
public class HelloController {
//원래 있던 코드들 ... 생략
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
Hello hello = new Hello();
hello.setName(name);
return hello;
}
public class Hello{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
}
- json방식 --> json 검색해보기(key value로 이루어진 구조)
- 실행 (http://localhost:8080/hello-api?name=spring)
- @ResponseBody 작동 원리
- @ResponseBody를 사용
- HTTP의 BODY에 문자 내용을 직접 전환
- viewResolver 대신에 HttpMessageConverter가 동작
- 기본 문자처리 : StringHttpMessageConverter
- 기본 객체처리 : MappingJackson2HttpMessageConverter
- byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음
참고 : 클라이언트의 HTTP Accept 헤더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서
HttpMessageConverter가 선택된다.
코드를 짜다가 뭔가 귀찮은데 싶으면 Comman + Shift + Enter
'Back-end > Spring' 카테고리의 다른 글
[Spring] 스프링 DB 접근 기술 (0) | 2021.09.21 |
---|---|
[Spring] 회원 관리 예제 - 웹 MVC 개발 (0) | 2021.09.21 |
[Spring] 스프링 빈과 의존관계 (0) | 2021.09.21 |
[Spring] 회원 관리 예제 - 백엔드 개발 (0) | 2021.07.29 |
[Spring] 프로젝트 환경설정 (1) | 2021.07.26 |
댓글