본문 바로가기

Java

[Spring] 스프링 부트 라우터(정적컨텐츠, MVC패턴, API 이용)

반응형

저번에 랜딩페이지만을 설정해보았다.

 

이번에는 다양한 페이지를 만들어 보도록 해보자.

 

스프링 부트에 라우터를 설정하는 여러가지 방법이 있다.

 

1. 정적컨텐츠를 이용

2. MVC패턴을 이용

3. API이용

 

 


1. 정적 컨텐츠를 이용하는 방법 

 

1) src > main > resources > templates 폴더에 hyuk.html파일 생성

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>혁이는 코딩 중</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1 th:text="'안녕하세요. '+${data}">여기는 안나옵니다</h1>
</body>
</html>

2번째 줄 xmlns~부분은 thymeleaf(템플릿  엔진)을 사용한다는 거다

th:문법은 thymeleaf문법이다. 관련 문법은 www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html에서 찾아볼수 있다.

 

 

2) src > main > java > com.hyuk.hyuktistory에 controller라는 패키지 생성 후 HelloController클래스 생성

 

3) HelloController 

package com.hyuk.hyuktistory.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 {

    // /hello로 접속하면 연결해줌
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "hello!");
        //resources>templates>hyuk파일을 리턴
        return "hyuk";
    }

}

@GetMapping("~~~")로 선언해주면 http://localhost:8080/~~~로 접속하면 아래를 연결해준다.

 

4) 실행

 

잘 실행되는 것을 확인할 수 있다.

 

 

 

2. MVC패턴을 이용

 

1) src > main > resources > templates 폴더에 hyuk-template.html파일 생성

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello-templates</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1 th:text="'hello. '+${name}">여기도 안나옵니다. 없어도 돼요.</h1>
</body>
</html>

2) HelloController

    // /hello-mvc로 접속하면 연결
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hyuk-template";
    }

위 코드를 추가해준다. @RequestParam의 Parameter를 name으로 받는다. required=true가 기본값이기 때문에 꼭 있어줘야하는 값이다.

 

3) 실행

당연히 안 된다. 왜냐하면 위에서 말했다시피 parameter인 name의 required가 true이므로 name값을 넣어 줘야한다.

 

 

name값을 주니까 잘 나오는 것을 확인할 수 있다.

 

 

3. API를 이용

 

1) HelloController

	@GetMapping("hello-api")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
//       View없이 "hyuk" +name 그대로 출력
        return "hyukiscoding" + name;
    }

위 코드만을 추가하고 실행해보자.

 

2) 실행

 

name꼭 값주자 !

 

 

3) HelloController

@GetMapping("hello-apis")
    @ResponseBody
    // Hello라는 객체 생성
    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;
        }
    }

위 코드를 추가하고 실행하면 어떤화면이 나올까 ?

 

 

(꿀팁으로 static class Hello{까지만 치고 ctrl+N을 누른후 getter and setter > ok를 누르면 바로 나온다)

 

 

 

4) 실행

위처럼 JSON형식으로 출력이 된다.

 

 

참고 사이트 : docs.spring.io/spring-boot/docs/2.4.3/reference/html/getting-started.html#getting-started

 

Getting Started

If you are getting started with Spring Boot, or “Spring” in general, start by reading this section. It answers the basic “what?”, “how?” and “why?” questions. It includes an introduction to Spring Boot, along with installation instructions.

docs.spring.io

 

 

반응형