SpringBoot/기초

스프링 웹 개발 기초

ewok 2023. 3. 10. 11:02

정적 콘텐츠

스프링 부트 정적 콘텐츠 기능

https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content

 

Spring Boot Features

Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest

docs.spring.io

 

<!DOCTYPE HTML>
<html>
<head>
    <title>static content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>

 

 

 

MVC와 템플릿 엔진

MVC : Model, View, Controller

 

Controller

HelloController.java

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

 

View

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present]

 

Controller에서 파라미터로 name을 주기로 했는데 없어서 그렇다.

 

이렇게 name을 넘겨주면 제대로 나온다.

 

 

 

API

@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
    return "hello" + name;
}

ResponseBody는 Http에서 body부에 데이터를 직접 넣어주겠다는 의미이다. (html의 <body>가 아니다.)

소스를 보면 html 태그 등이 하나도 없이 그냥 문자가 그대로 들어간다.

 

@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이라는 방식이다.