(Controller는 모든 요청을 가장 먼저 받아온다)
@GetMapping
: 받은 요청(get 요청, post 요청..)에 대한 매핑을 찾는다는 의미
(@GetMapping, @PostMapping, @RequestMapping이 있다)
return "viewName";
: Spring Boot 템플릿엔진 기본 viewName 매핑 방식이다(view resolver)
: viewName을 작성하면 자동으로 resources:templates/ + {viewName} + .html(자동으로 붙는다)으로 된다.
→ ex. mapper.html
: templates에서 작업을 해야한다.(동적인 페이지는 templates 영역에 페이지를 만들기 때문/ static은 정적인 페이지를 만들 때)
{viewName}
: 리턴해주는 스트링 타입의 문자열이 들어간다.
view resolver
:페이지 컨트롤러가 리턴한 뷰 이름에 해당하는 뷰 객체를 매핑하는 역할을 한다.
상단의 <html>
부분에 <html xmlns:th="http://www.thymeleaf.org">
를 넣는다
→thymeleaf를 사용하기 위해
<p th:text="'안녕하세요' + ${key}"></p>
th
: thymleaf사용할 것이라는 걸 의미한다.
text
: text를 사용할 것이라는 걸 의미한다.
넘겨진 키값 사용할 땐 ${}을 사용한다.
"" 안에 문자열 적을 땐 ''(홑따옴표)를 적어야한다.
이번엔 파라미터로 넘겨받는 값이 있을 경우를 작성해보자
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name")String name, Model model) {
// 어노테이션(@RequestParam)으로 파라미터값 받아온다.
//"name"은 키값(파라미터의 name과 동일해야함), SpringMVC은 밸류값(String name)
model.addAttribute("name", name);
//파라미터로 넘어온 값을 "name"이라는 키값에 담아준다
return "hello-template";
}
위의 경우는 파라미터 값이 반드시 있어야 하는 경우이다.
/*
* @RequestParam
* - required : 파라미터 값 필수 여부
* true -> 필수(default), false -> 필수 아님
* - defaultValue : 파라미터 값이 없을 경우 기본으로 들어갈 값
*/
@GetMapping("hello-mvc")
public String helloMvc2(@RequestParam(value="name", required = false,
defaultValue = "required test 기본값") String param, Model model) {
model.addAttribute("name", param);
return "hello-template";
}
위의 경우는 파라미터 값이 없으면 defaultValue가 출력된다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
결과창
파라미터 값이 없을 경우
파라미터 값이 있을 경우