Spring

[Spring] 웹 기초

songsua 2025. 3. 1. 20:37

View 환경 설정

Spring 에서는 /resource/static/index.html 에 저장할 경우 Welcome 페이지로 사용 가능하다.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    
    @GetMapping("/hello") // "/hello" 경로로 GET 요청이 오면 실행
    public String hello(Model model) {
        model.addAttribute("message", "Hello, Spring!");
        return "hello"; // "hello.html" 뷰를 반환
    }
}

 

Model이란?

  • 뷰(View)와 컨트롤러(Controller) 사이에서 데이터를 전달하는 역할
  • 컨트롤러에서 데이터를 Model에 추가하면, 뷰(HTML, Thymeleaf 등)에서 해당 데이터를 사용할 수 있다.

1️⃣ model.addAttribute("message", "Hello, Spring!");

  • "message"라는 키(key)에 "Hello, Spring!" 값을 저장함.
  • 이 값은 뷰(HTML)에서 사용 가능.

2️⃣ return "hello";

  • 뷰 이름("hello")을 반환하면, templates/hello.html이 랜더링됨.
  • 보통 Thymeleaf 같은 템플릿 엔진을 사용하여 HTML과 연결.

 

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Hello</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${date}" > 안녕하세요. 손님 </p>
<a href="/hello">hello</a>

</body>
</html>

이 HTML 파일은 Thymeleaf 템플릿 엔진을 사용하는 뷰 파일로, Spring Boot에서 동적으로 데이터를 주입하여 화면을 렌더링하는 역할을 한다.

 

<p th:text="'Hello, ' + ${date}"> 안녕하세요. 손님 </p>

  • th:text는 Thymeleaf에서 사용되는 속성
  • 컨트롤러에서 전달된 데이터(date)를 사용하여 동적으로 HTML을 변경
  • + 연산자를 사용해 "Hello, " + ${date} 문자열을 출력
  • 만약 date="Spring User"라면, 최종적으로 **Hello, Spring User**가 화면에 표시됨.

<a href="/hello">hello</a>

  • 클릭하면 /hello 경로로 이동하는 링크(button) 역할을 함.
  • /hello로 GET 요청을 보내 컨트롤러의 @GetMapping("/hello")가 실행됨.
  • href는 HTML의 <a>(앵커) 태그에서 사용되는 속성으로, 클릭했을 때 이동할 URL(링크) 을 지정하는 역할을 한다.

 

 

으로 출력된다.

return "hello" 라고 적었는데, templates디렉터리에 있는 hello.html 을 찾아서 연결한다.

컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버가 화면을 찾아서 처리한다.

resources 디렉터리 밑에 있는 templates 에 +{viewName} + . html 에 맵핑되도록 되어 있다. 

 

정적 컨텐츠 이미지 찾아가는 과정
1. 웹브라우저에서 url 로 localhist:8080/hello.static.html 을 친다

2. 제일 먼저 controller 디렉터리의 하위를 찾아본다(제일 우선순위가 높음)

3. controller 에 없을 경우, resources 안에 있는 것을 찾는다.

 

 

 

MVC 와 템플릿 엔진

MVC :  Model, View, Controller 을 합친 것
Controller: 비즈니스 로직돠 서버 뒷단 관련된 것들을 처리하는 것

View : 화면에 관련 된 것들

package org.example.springstudy.controller;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("date" , "date 테스트중입니다!!");
        return "hello";
    }

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

    }
}

 

설명

  • @GetMapping("hello-mvc")
    → 사용자가 http://localhost:8080/hello-mvc로 요청하면 실행됨.
  • @RequestParam(value = "name", required = false) String name
    쿼리 파라미터 name을 받아서 저장.
    • 예) http://localhost:8080/hello-mvc?name=홍길동
      • name 값에 "홍길동"이 저장됨.
      • 이 부분에서 **required = false**는 해당 요청 파라미터(name)가 없어도 오류가 발생하지 않도록 설정하는 것
      • 기본적으로 @RequestParam은 필수값으로 동작함 (required = true가 기본값).
      • name이 없으면 오류 발생! False 인 경우 name 이 없어도 오류가 발생하지 않는다.
        예제:
        • ✅ /hello-mvc?name=홍길동 → 정상 작동 (name = "홍길동")
        • ❌ /hello-mvc → 오류 발생! (MissingServletRequestParameterException)
  • model.addAttribute("name", name);
    → name 값을 hello-template.html에서 사용할 수 있도록 추가.
  • return "hello-template";
    → hello-template.html 템플릿을 반환.

 

 

API  
객체를 반환하여 사용하는 것

@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
    Hello hello = new Hello();
    hello.setName(name);
    return hello;
}
static class Hello {
    private String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

 

Json 방식으로 나오는 것을 볼 수 있다.

 

1. @GetMapping("hello-api")

  • http://localhost:8080/hello-api?name=홍길동 처럼 GET 요청을 받을 때 실행됨.

2. @ResponseBody

  • @ResponseBody를 사용하면 HTML이 아니라 JSON 형태로 데이터를 반환함.
  • return hello; 부분이 JSON 형태로 변환되어 응답됨.

3. @RequestParam("name") String name

  • 클라이언트가 ?name=홍길동처럼 name 값을 전달하면 해당 값을 String name에 저장함.

4. Hello 객체 생성 및 반환

 
  • 새로운 Hello 객체를 만들고, setName(name)을 호출하여 name 값을 저장.
  • 객체 자체를 반환하면, Spring Boot가 JSON 형식으로 자동 변환해줌.

위에 처럼 객체를 받을 경우에는 다른 라이브러리가 실행된다.

기본 문자처리: `StringHttpMessageConverter`

기본 객체처리: `MappingJackson2HttpMessageConverter`

요즘은 json 만 사용한다고 생각하면 된다.