core 프로젝트로 스프링 부트와 thymeleaf 맛보기

전영덕·2023년 4월 29일
0

Springboot

목록 보기
3/13

1. application.properties셋팅

#port 수정
server.port=9090

#한글
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true

#thyme
spring.thymeleaf.cache=false

기본적인 셋팅읋 해주었다.

2. index.html 부터 시작

  • static폴더 아래에 index.html을 만들어서 원래 알던 HTML파일과 같게 한다.
    여기서
<a href="/hello">Hello</a>

를 통해 "/hello" 로 요청을 보내게 하자.
JSP때 했던 것 처럼 먼저 프론트 컨트롤러가 필요하다.
여기서는 HelloController.java를 만든다.

3. HelloController.java

  • 프론트 컨트롤러를 만들었으면 @Controller를 선언해야한다.
  • 이제 요청을 받으면 실행할 메서드를 만들 것이다.
	@GetMapping("hello")
	public String hello(Model model) {
		System.out.println("hello mapping");
		model.addAttribute("data", "hello mapping!!!");
		return "hello";

@GetMapping으로 요청받은 url을 파싱해온다.
data하나 넘길꺼니까 Model model 을 파라미터로 넣어준다.
return "hello"; 이부분은 trmplates폴더 아래에 hello.html이라는 파일을 찾아가라는 말이다.

  • 주의 사항
    return "forward:hello";
    이렇게 써야하는게 맞지만 생략해도된다. 즉 디폴트 값이 포워드 방식이다.
    return "redirect:/hello";
    이러면 리다이렉트 방식으로 보내는 것인데 이렇게 하면 무한 반복문이 돌게 된다.

4. hello.html

data에 담긴 문자열을 기존의 안녕하세요, 손님 이라는 text에 덮어쓰게 해주는 것이 thymeleaf이다.
제일 많이 쓰게 되며, th:text="~~~" 라고 쓰면 된다.

5. hello-template.html

주소창에서 직접
localhost:9090/hello-mvc
라고 호출을 한다.
그러면 HelloController.java에서

@GetMapping("/hello-mvc")
	public String helloMvc(@RequestParam(value="name", required=false, defaultValue = "required value") String name, Model model) {
		model.addAttribute("name", name);
		return "hello-template";
	}

프론트 컨트롤러를 통해 hello-template.java를 호출할 것이다.

이 때 @RequestParam이라해서 3가지정도의 특성을 소개했다.

@Request.Param("name") : 기본 name이라는 key값을 파싱한다. 욥션을 넣어 줄 수 있다.

  • required : 파라미터 값 필수 여부, true : 필수(default), false : 필수가 아님
  • defaultValue : 파라미터 값이 없을 경우, 기본으로 들어갈 값

6.MemberController.java

여기서 한발 자국 더 나아갔다.
MemberController.java파일을 만들어서 @Controller선언을 해주고
member라는 요청을 받았을 경우의 상황이다.
MemberDTO라는 클래스를 하나만들고 생성자를 통해 설정을 한다.
model에 담아 thymeleaf/member 라는 html파일로 리턴한다.

DTO에 담긴 정보 가져오는 방법

  • 이거 참 유용할 것 같으면서도 다른 방법이 또 있을 것 같다.
		<tr th:object=${member}>
			<td><span th:text="*{no}"></span></td>
			<td><span th:text="*{name}"></span></td>
			<td><span th:text="*{phone}"></span></td>
		</tr>

이렇게 객체에서의 정보를 *{ } 을 통해 꺼내올 수 있다.

0개의 댓글