View 환경설정
- resources / static / index.html
- resources / static 폴더 하위에 index.html 파일을 올려두면 스프링부트에서 해당 html 파일을
Welcome Page로 인식하도록 기능을 제공한다.
* spring.io 참고
정적 컨텐츠, MVC와 템플릿엔진, api
1). 정적 컨텐츠
- 정적컨텐츠는 스프링부트에서 자동으로 기능을 제공한다.
- resources / static / hello-static.html 파일 생성 (컨트롤러 x)
- 주소창에 localhost:8080/hello-static.html 입력후 엔터
1. 컨트롤러에 작성된 @RequestMapping("hello-static") 을 찾음 -> 찾지 못함
2. rsources / static / hello-static.html 을 찾음
3. 발견한 html 파일을 그대로 리턴하여 보여준다.
2). MVC와 템플릿엔진
- MVC : Model View Controller
- hello-template.html 파일 생성
<HTML>
<p th: text= "hello" + ${name}> hello! empty </p>
</HTML>
- Controller 파일 생성
@Controller
public Class helloController{
@RequestMapping("hello-MVC")
public String helloMVC( @RequestParam("name") String name, Model model){
model.attribute("name", name);
return "hello-template";
}
}
- 주소창에 localhost:8080/hello-MVC?name=Spring!!!!! (Get 방식)
1. 컨트롤러에서 hello-MVC로 작성된 requestMapping이 있는지 확인
2. 파라미터확인 후 모델객체에 name 이라는 명칭으로 파라미터를 담음
3. hello-template문자열을 리턴하면서 해당 html의
${name}은 넘겨진 모델에 담긴 name의 값을 꺼내와 치환하여 사용자에게 보여준다.
이것이 template 엔진의 역할이다.
3). Api
- Controller작성후 RequestMapping 어노테이션 작성후 바로 하단에 @ResponseBody 어노테이션을 추가한다.
- 주소창에 localhost:8080/hello-string?name=string!!! 입력후 엔터
- @RequestMapping("hello-string")
@ResponseBody
public Hello helloString(@RequestParam("name") String name){
Hello hello = new Hello(); // static Class를 컨트롤러에 추가한 이후에 선언하여 사용함
hello.setName(name);
return hello; // 객체를 리턴하며, 리턴된 객체는 화면에 JSON 형식으로 출력된다
// 화면에 보여지는 항목 {"name" : "string!!!"}
}
- 컨트롤러에 @ResponseBody 어노테이션을 추가한다면, 컨트롤러에 접근했을때 viewResolver가 작동하지 않는다.
- viewResolver 대신에 HttpMessageConverter가 동작하며, HTTP 바디에 문자내용을 직접반환한다 (HTML BODY가 아님)
- 객체를 리턴하는 것을 일반적으로 api 방식이라고 한다.
- 기본문자처리 : StringHttpMessageConverter
- 기본객체처리 : MappingJackson2HttpMessageConverter
'SPRING' 카테고리의 다른 글
[SpringBoot] 스프링빈 의존관계 (0) | 2021.10.11 |
---|---|
[Srping] web.xml (0) | 2021.08.24 |
Spring 라이프 사이클 (1) | 2021.08.20 |
SPRING 프레임워크 개발환경 세팅 (0) | 2021.08.09 |