- 컨트롤러 생성. (HelloController.java)
- 코드 해석
- @GetMapping("hello-mvc")
: get 방식으로 hello-mvc라는 값이 넘어온다면 아래의 코드를 실행시키겠다. - public String helloMvc(@RequestParam("name") String name, Model model)
: 함수 helloMvc 를 선언할 것이며 해당 함수에서는 파라미터로 얻은 name 값을 name이라는 문자열 변수에 담을 것이며model이라는 변수로 Model을 사용하겠다. - model.addAttribute("name", name);
: 모델 안에 속성을 추가하겠다. name이라는 속성에 방금 얻어온 파라미터 name 값을 넣어주겠다. - return "hello-template";
: 위에서 선언한 model을 사용할 수 있는 템플릿 hello-template 파일로 반환하겠다.
- @GetMapping("hello-mvc")
- 코드 해석
package hello.hellospring.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HelloController { @GetMapping("hello-mvc") public String helloMvc(@RequestParam("name") String name, Model model) { model.addAttribute("name", name); return "hello-template"; } }
- 템플릿 생성 (hello-template.html)
- 코드 해석
- <html xmlns:th:"http://www.thymleaf.org">
: html을 사용할 것이며 다음 html에서 thymleaf를 사용하겠습니다. - <p th:text="hello + ${name} "> hello! empty </p>
: p 태그를 사용할 것이며 해당 태그 안의 텍스트는 "hello + (컨트롤러에서 보낸 모델의 속성 name의 값)이며
만약 해당 html을 서버를 통하지 않고 그냥 열어본다면 hello! empty라는 텍스트를 반환하겠습니다.
- <html xmlns:th:"http://www.thymleaf.org">
- 코드 해석
<html xmlns:th="http://wwww.thymleaf.org"> <body> <p th:text="'hello '+ ${name}"> hello! empty </p> </body> </html>
- 동작 확인
- 위처럼 코드를 작성하고 url을 입력한다면 다음과 같은 결과를 얻을 수 있다.
- 파라미터 name 값을 사용한다고 컨트롤러에 명시했기 때문에 쿼리스트링 값으로 name을 선언해줘야 한다
- 동작 원리
트러블 슈팅
- 파라미터를 선언하지 않는다면
- 다음과 같은 에러 메시지와 함께 원하는 view를 볼 수 없다
- 다음과 같은 에러 메시지와 함께 원하는 view를 볼 수 없다
- 파라미터를 선언하지 않았을 때에도 에러가 발생하지 않게 하려면?
- 다음과 같이 @RequestParam의 값을 바꿔주면 된다
@GetMapping("hello-mvc") public String helloMvc(@RequestParam(value = "name", required = false) String name, Model model) { model.addAttribute("name", name); return "hello-template"; }
- 이전과 같이 @RequestParam("name")이라고 입력한 것은 다음과 같은 의미를 가지고 있다.
@RequestParam(value = "name", required = true)
: 해석) 나는 파라미터 name의 값을 받아올 것이며, 해당 파라미터는 필수이다. - 에러가 발생하지 않는 것을 확인할 수 있다
- 다음과 같이 @RequestParam의 값을 바꿔주면 된다
728x90
'Programming > Spring Boot' 카테고리의 다른 글
[Spring Boot] 정적 컨텐츠 만들기 (vscode) (0) | 2024.03.07 |
---|---|
[Spring Boot] 빌드 / 실행시키기 (vscode) (0) | 2024.03.07 |
[Spring Boot] View 환경설정 (vscode) (0) | 2024.03.07 |
[Spring Boot] spring boot 를 vscode 에서 빌드 및 실행하는 방법 (0) | 2024.03.07 |