[스프링부트] 4. 스프링부트 맛보기 2

문정준's avatar
Mar 13, 2025
[스프링부트] 4. 스프링부트 맛보기 2

1. New Project

  • 설정은 이전과 똑같이 세팅
notion image
 
notion image
 

2. 폴더 / 파일 생성

  • repository, controller, model
    • UserRepository, UserController, User
  • resources → template → user → info.mustache
notion image
 

3. 코드 작성

  • User
package org.example.second.model; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public class User { private int id; private String username; private String email; }
 
  • UserRepository
package org.example.second.repository; import org.example.second.model.User; public class UserRepository { public User findOne() { // select * from user_tb where id = 1; // given data return new User(1, "ssar", "ssar@nate.com"); } public User findTwo() { // select * from user_tb where id = 2; // given data return new User(2, "cos", "cos@nate.com"); } }
 
  • UserController
package org.example.second.controller; import org.example.second.model.User; import org.example.second.repository.UserRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; // 리턴되는 값의 경로를 찾아 (./resources/template/user/info) 파일 내용을 읽은 후 버퍼에 담음 // RestController : 리턴되는 값을 바로 버퍼에 담음 @Controller public class UserController { UserRepository userRepository = new UserRepository(); @GetMapping("/user/1") public String findOne(Model model) { User user = userRepository.findTwo(); // Hashmap : 키 값으로 모델 (user = value) 값을 들고갈 수 있음 model.addAttribute("model", user); return "user/info"; } @GetMapping("/v2/user/1") public @ResponseBody String findOneV2() { User user = userRepository.findOne(); return """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Info Page</h1> <hr> <div> ${user.id}, ${user.username}, ${user.email} </div> </body> </html> """.replace("${user.id}",user.getId()+"") .replace("${user.username}",user.getUsername()+"") .replace("${user.email}",user.getEmail()+""); } }
 
  • info.mustache
    • html 내부에 자바 코드를 들고 갈 수 있음 : Template Engine
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Info Page</h1> <hr> <div> {{model.id}}, {{model.username}}, {{model.email}} </div> </body> </html>
 
 

결과

  • localhost:8080/user/1
notion image
 
  • localhost:8080/v2/user/1
notion image
 
✏️

Controller vs RestController

  • Controller : 리턴받은 값의 경로를 찾아 파일을 읽어 버퍼에 담음
  • RestController : 리턴받은 버퍼에 담음
 
Share article

sxias