[SpringBoot] Controller에서 페이지 띄우기 기본
어질어질 하구나
Retrofit으로 통신하려다가 백을 만져보고 있는 중이다.. 어질어질하다..
무튼.. hello를 던지면 바로 hello.html 페이지가 표출되도록 하는 것이다.
정적으로 페이지 띄우기
[src/main/resources/templates/hello.html]
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" http-equiv="Content-Type" content="text/html">
<title>Title</title>
</head>
<body>
<p th:text="'안녕하세요... ' + ${data}">손님~~~!!</p>
</body>
</html>
컨트롤러에서 설정할 코드
package kr.co.cavedwellers.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello..!!!");
return "hello";
}
}
@Controller로 어노테이션해주면 Spring자체에서 알아서 객체를 만든다.
그리고 일단 최종 baseUrl을 접속하게 되면 띄어주는 것은 static폴더에서 설정한 index.html이며,
: localhost:8080/hello
이렇게 전달하면 DemoController에서 @GetMapping이 "hello"를 찾고 해당 어노테이션 붙은 함수를 실행시키게 된다.
return할 때 보여주는 것은 hello.html이며, 타임리프(thymeleaf)로 "data"를 키로, 그리고 우측 값을 값으로 html에 적용하게 된다.
그래서 아래의 ${data}안에 위의 hello..!! 가 적용되게 된 것
<p th:text="'안녕하세요... ' + ${data}">손님~~~!!</p>
동적으로 페이지 띄우기
dynamic.html 페이지를 만든다
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Dynamic</title>
</head>
<body>
<p th:text="'dynamic name:'+ ${name}">홍길동</p>
</body>
</html>
기본 값은 '홍길동'이다.
컨트롤러에서 다음과 같이 설정
@GetMapping("dynamic")
public String dynamic(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "dynamic";
}
localhost:8080/dynamic을 호출하면 dynamic함수가 실행되고,
@RequestParam인 'name'에 값을 넣으면 이전 dynamic.html에 'name'에 값이 전달된다.
: http://localhost:8080/dynamic?name=네안데르
페이지가 아닌 문자열 띄우기
: static, template에서 만든 html이 아닌 자체 문자열을 표출하는 방법이다
// 페이지 없이 바로 출력
@GetMapping("direct")
@ResponseBody
public String directName(@RequestParam("name") String name) {
return "directName : " + name;
}
그리고 URL에
: direct?name=
: http://localhost:8080/direct?name=네안데르
이렇게 전달하면 된다.