스프링 웹 방식
- 정적 컨텐츠
정적 컨텐츠는 HTML 파일을 그대로 띄워주는 것을 말한다
<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
resources/static/hello-static.html에 넣어주고
localhost:8080/hello-static.html 검색하면 아래와 같이 값이 띄워진다
웹 브라우저에서 내장 톰캣 서버에 요청하면 스프링 컨테이너에 맵핑 해야하지만 컨트롤러가
때문에 html 주소로 바로 연결하여 웹 브라우저에 응답하게 된다
- MVC와 템플릿 엔진
MVC : Model, View , Controller
MVC 모델은 Controller를 통해 연결해주는 것을 말한다
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
} //Controller
hello! empty
//View
get방식으로 진행하였으며 RequestParam을 사용하여 url에 정보를 입력해주는 방법을 사용하였다
변수로는 내용을 입력할 name, view단에 응답해줄 model을 사용하였고
key value 방식으로 model을 통해 view에 전달을 해주었다
return 은 view단 html 파일명을 지정해준다
구동순서는
웹브라우저에서 내장 톰켓서버에 hello-mvc로 연결해주면 Controller로 들어가
return 값에 있는 hello-template로 model(name:”입력값”) 으로 전달해준다
viewResolver를 통해 Thymeleaf 템블릿 엔진 처리된 후 HTML 변환 후 화면에 띄워지게 된다
- API
json형식으로 보내지며 @ResponseBody를 사용하여 viewResolver (Tyymeleaf 템플릿) 없이 구동됨
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
첫번째 방법은 값을 RequestParam 에 넣어줘서 View 없이 사용하는 ResponseBody 기본 형식
@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;
}
}
두번째 방법은 getter/setter 방식을 사용하여 구동하는 방식이다
객체를 사용하므로 객체를 반환하면 객체가 JSON으로 변환된다
구동방식은
웹 브라우저에서 내장 톰켓 서버로 연결되고 helloController에 ResponseBody 로 return 값이
주어지면 viewResolver대신에 HttpMessageConverter로 연결되어
JsonConverter를 통하여 제이슨 형태로 웹 브라우저에 값 전달이 된다
'프로그래밍언어 > Java' 카테고리의 다른 글
스프링 자동 의존관계 , 수동 의존관계 (0) | 2022.01.13 |
---|---|
스프링 회원 조회 기능 구현 (0) | 2022.01.12 |
[JAVA] 객체 생성과 파괴 (0) | 2022.01.06 |
[JAVA] OCR 기본활용 (0) | 2021.12.29 |
SPRING MVC모델 게시판 (0) | 2021.11.22 |
댓글