웹 개발 방식
- 정적 컨텐츠 : 고정된 파일을 그대로 전달
- MVC와 템플릿 엔진 : html을 서버에서 변형해서 전달
- API : 서버끼리 통신할 때 자주 사용
MVC와 템플릿 엔진
- 컨트롤러에서는 내부로직에 집중, 뷰에서는 화면을 그리는데 집중함
# Get 방식으로 데이터 받아 사용하기
▽ 컨트롤러에 아래 코드 추가
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model){
model.addAttribute("name",name);
return "hello-template";
}
▽ resources/templates/hello-template.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello-template</title>
<meta http-equiv="Content-Type"content="text/html; charset=UTF-8"/>
</head>
<body>
<p th:text="'hello!' + ${name}">hello. empty</p>
</body>
</html>
- localhost:8080/hello-mvc?name= 설정해주어야함
- 템플릿 엔진에서는 viewResolver에서 htrml 파일을 변환해서 웹 브라우저에게 전송
API 방식
▽ 컨트롤러에 아래 코드 추가
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name){
return "hello, " + name;
}
- @ResponseBody를 사용하면 HTTP의 BODY에 문자 내용을 직접 반환
- viewResolver를 사용하지 않고, HttpMessageConverter가 동작
- 소스보기 하면 html 태그 없이 내용만 그대로 보임
- 기본 문자처리: StringHttpMessageConverter
▽ 컨트롤러에 아래 코드 추가
@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;
}
}
- 기본 객체 처리 : MappingJackson2HttpMessageConverter
- 객체 반환하면, 객체가 JSON 방식(key-value) 으로 변환됨
'BACKEND > Spring' 카테고리의 다른 글
[ 인프런 - 스프링 입문 (김영한님) 강의 정리 ] 1. 프로젝트 환경설정 (1) | 2022.12.25 |
---|