[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술] 02. 스프링 웹 개발 기초

Turtle·2024년 6월 7일
0
post-thumbnail

📚️정적 컨텐츠

출처 : Spring documentation(static contents)

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath.

기본적으로 Spring Boot는 클래스 경로에 있는 /static(또는 /public, /resources 또는 /META-INF/resources)라는 디렉터리의 정적 콘텐츠를 제공한다.
WelcomePageHandlerMapping 클래스가 동작하여 웰컴페이지에 대한 내부 로직이 동작하여 발생하는 것으로 이해할 수 있다.

2024-06-08T00:29:20.831+09:00  INFO 14412 --- [hello-spring] [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]

1) 먼저 hello-static과 관련된 컨트롤러를 찾는다.

2) 없으면 그 다음 정적 컨텐츠를 보관하는 resources: static/에서 hello-static이름을 가진 정적 컨텐츠를 웹 브라우저에 보여준다.

❓/static 디렉터리에 index.html이란 이름의 정적 컨텐츠가 없다면?

This application has no explicit mapping for /error, so you are seeing this as a fallback.

위의 문장이 표시되는 Whitelabel Error Page가 보여지게 된다.

❗hello-static.html 정적 컨텐츠가 제공되지 않는 문제 발생

해당 부분에 대한 내용을 찾아보니 아래 링크에서 다음과 같은 답을 얻을 수 있었다.

출처 - 인프런 커뮤니티

netstat -ano | findstr 8080 → 현재 8080포트로 실행중인 프로세스 ID를 찾기
taskkill /f /pid 프로세스ID → 프로세스 ID로 프로세스 강제 종료하기

위의 순서를 거치고 나니 정상적으로 실행되는 것을 확인할 수 있었다.

📚️MVC와 템플릿 엔진

Controller(컨트롤러)

package hello.hello_spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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("data", "hello");
        return "hello";
    }

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

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

hello-mvc 컨트롤러를 보면 @GetMapping 어노테이션을 사용하였고 @RequestParam 어노테이션을 사용하여 파라미터를 요구하는 것을 볼 수 있는데 URL에 http://localhost:8080/hello-mvc로 입력하여 파라미터가 없다는 것을 나타내는 것이다.

파라미터를 넣으려면 URL을 http://localhost:8080/hello-mvc?name=test와 같이 파라미터를 넣어 표시해주면 정상적으로 동작되는 것을 확인할 수 있다.
@RequestParam 어노테이션은 HTTP 요청 파라미터의 이름으로 바인딩하여 그 값을 변수에 저장하는 역할을 한다.

📚️API

기존 정적 컨텐츠나 MVC와 템플릿 엔진과 달리 API 방식을 사용하면 JSON 형태의 데이터를 반환할 수 있게 된다. @ResponseBody@RequestParam 어노테이션을 사용하면 된다.

@ResponseBody@RequestBody 어노테이션은 클라이언트에서 서버로 필요한 데이터를 요청하기 위해 JSON 데이터를 서버로 보내고 서버에서 HTTP 요청 본문에 담긴 값을 자바 객체로 변환시켜 객체에 저장한다.

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

    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloMember(@RequestParam("name") String name, @RequestParam("id") Long id) {
        Hello hello = new Hello();
        hello.setId(id);
        hello.setName(name);
        return hello;
    }

    static class Hello {
        private String name;
        private Long id;

        public String getName() {
            return name;
        }

        public Long getId() {
            return id;
        }

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

        public void setId(Long id) {
            this.id = id;
        }
    }
}

🔒출처

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

0개의 댓글