📌 Controller 언제 사용해야 할까?
- 웹 애플리케이션에서 HTML 페이지를 반환할 때
- 템플릿 엔진(Thymeleaf, Mustache 등)과 함께 사용할 때
1. 프로젝트 만들기


2. 코드 작성
package org.example.second.repository;
import org.example.second.model.User;
public class UserRepository {
public User findOne(){
// select * from user_tb where id = 1;
return new User(1,"ssar", "ssar@nate.com");
}
public User findTwo(){
// select * from user_tb where id = 2;
return new User(2,"cos", "cos@nate.com");
}
}
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;
}
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;
@Controller
public class UserController {
UserRepository userRepository = new UserRepository();
@GetMapping("user/1")
public String findOne(Model model){
//templates/user/info.mustache를 리턴
User user = userRepository.findTwo();
// 키, 밸류를 넣고 그 결과를 리턴
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());
}
}
템플릿 엔진 → HTML에 JAVA 코드를 넣는 것
<!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>

Share article