Post

springboot로 Rest api 만들기 HelloWorld

사용환경

공부한 내용을 되새겨볼겸 적어보았다.

stackInfo
toolIntelliJ Community
langJAVA
JDK11


Create a Project

내가 참고한 블로그에선 spring initializer 사이트를 이용하였는데 나는 그냥 인텔리제이를 사용하는데 익숙해져야 하기도 하고 그래서 인텔리제이 내에서 생성하였다.

생성방법

image

인텔리제이 창에서 [New Project]를 선택하면 해당 창이 뜬다. 사진에서 설정한대로 따라하면 된다.

SettingsInfo
langJava
TypeGradle
JDK11
Java11
PackagingJar

프로젝트 이름은 맘에드는데로 아무거나 하면 된다.

[Next]를 누르면

image

해당 창이 뜨는데 여기서

  • Spring Web
  • Spring Security
  • Spring Boot Actuator
  • Spring Data JPA
  • Spring Data Redis (Access + Driver)
  • Lombok
  • MySQL Driver
  • H2 Database

를 추가해주면 된다.

다 완료됐으면 [Create] 버튼을 클릭하여 프로젝트를 생성한다.

프로젝트 생성이 완료되면 [run]을 클릭하여 실행한다. 성공적으로 실행되면

http://localhost:8080 링크로 접속한다.

image

위 화면이 뜨면 성공한 것이다.


Print HelloWorld

Package

자바에서 패키지는 클래스와 인터페이스의 집합을 의미한다. 협업 시 서로 작업한 클래스 사이에서 발생할 수 있는 이름 충돌 문제도 패키지를 이용하면 피할 수 있다.

자바에서 패키지는 물리적으로 하나의 디렉터리를 의미한다. 따라서 하나의 패키지에 속한 클래스나 인터페이스 파일은 모두 해당 패키지 이름의 디렉터리에 포함되어 있다. 이러한 패키지는 다른 패키지를 포함할 수 있으며, 이때 디렉터리의 계층 구조는 점(.)으로 구분된다.

예시로

1
2
package com.example.pepega.helloworld.java;
package com.example2.pepega.helloworld.java;

​가 있다.

클래스 이름(helloworld)은 같지만 package 이름이 다르므로 다른 class로 구분된다.


@SpringBootApplication

SpringBoot에서는 @SpringbootApplication (annotation이라고 한다.) 선언만으로 대부분 설정이 자동으로 이루어진다. 하단은 boot실행을 위한 Application 설정 파일이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.pepega;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PepegaApplication {

	public static void main(String[] args) {
		SpringApplication.run(PepegaApplication.class, args);
	}

}

port 지정

image

[resources] 우클릭 -> [New] -> [File] 클릭

1
application.yml

이라는 이름의 파일을 생성한 후 port를 지정한다.

1
2
server:
  port: 8080

1024번 포트 이하는 특권(privileged) 포트로 지정되어 있어 root 권한으로만 사용할 수 있는 port이다.


controller 패키지 생성

controller 패키지를 생성한다.

image

[com.example.프로젝트_이름] 우클릭 -> [new] -> [Package]를 클릭한다. 나는 이미 생성한 뒤라서 사진에 controller가 뜨는 것을 볼 수 있다.

controller 패키지에 ApiPracticeController.java를 생성한다. 저 이름이 맘에들지 않는다면 다른 원하는 이름으로 지어도 상관없다.

혹시 자바파일을 생성하고 난 후

1
package com.example.프로젝트_이름.controller;

패키지 이름이 위와 같지 않다면 수정해준다. 수정은 해당 파일 우클릭 -> [Refactor] -> [Rename]이다.

image

대충 이런 식으로 되어있어야 한다.


controller 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.example.api_practice.controller;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/*
@Controller
Spring에 해당 Class가 Controller 임을 알려주기 위해 class명 상단에 @Controller를 붙여준다.
 */

@Controller
public class ApiPracticeController {

    /*
    @GetMapping("RequestURI")
    GetMapping을 붙이면 해당 주소의 Resource를 이용하기 위해서

    Get method(get, post) 로 호출해야 한다는 뜻이다.
     */

    /*
    @ResponseBody
    결과를 응답에 그대로 출력한다는 의미다.

    @ResponseBody를 지정하지 않으면 return에 지정된 "helloworld" 이름으로 된 파일을 프로젝트 경로에서 찾아 화면에 출력한다.
     */

    //화면에 helloworld 출력
    @GetMapping(value = "/helloworld/string")
    @ResponseBody
    public String helloworldString() {
        return "helloworld";
    }

    //화면에 {message:"helloworld"} 출력
    @GetMapping(value = "/helloworld/json")
    @ResponseBody
    public Hello helloworldJson() {
        Hello hello = new Hello();
        hello.message = "helloworld";
        return hello;
    }

    //화면에 helloworld.ftl의 내용이 출력
    @GetMapping(value = "/helloworld/page")
    public String helloworld() {
        return "helloworld";
    }

    /*
    @Getter
    @Setter
    선언되어있는 변수를 알아서 Getter, Setter(lombok)가 되도록 지정해준다.
     */

    @Setter
    @Getter
    public static class Hello {
        private String message;
    }
}
  • @Controller

    • Spring에 해당 Class가 Controller 임을 알려주기 위해 class명 상단에 @Controller를 붙여준다.
  • @GetMapping(“RequestURI”)

    • GetMapping을 붙이면 해당 주소의 Resource를 이용하기 위해서 Get method(get, post) 로 호출해야 한다는 뜻이다.

      1
      
        http://localhost:8080/helloworld/json
      
    • 웹 브라우저에 위 주소창을 실행하면 Get방식으로 호출된다.

    • /helloworld/ json을 Mapping하고 있는 메서드( public Hello helloworldJson() )가 실행된다.

  • @ResponseBody
    • 결과를 응답에 그대로 출력한다는 의미다.

    • @ResponseBody를 지정하지 않으면 return에 지정된 “helloworld” 이름으로 된 파일을 프로젝트 경로에서 찾아 화면에 출력한다.

  • @Getter
    @Setter

    • 선언되어있는 변수를 알아서 Getter, Setter(lombok)가 되도록 지정해준다.


Create ftl File

image

resource 파일 아래 templates 우클릭 -> [New] -> [File]을 클릭하여

1
helloworld.ftl

을 생성한다.

ftl 파일 내에

1
HelloWorld

작성

application.yml 에 하단 내용을 추가한다.

1
2
3
4
spring:
  freemarker:
    template-loader-path: classpath:/templates/
    suffix: .ftl

build.gradle 에 하단 내용을 추가한다.

1
implementation 'org.springframework.boot:spring-boot-starter-freemarker'


실행결과

image

  • User name: user
  • Passworld: 밑의 콘솔 확인

image

아래는 로그인 후 뜨는 화면이다.

image

로그인이 됐으면 각각 주소를 실행한다.

1
2
3
http://localhost:8080/helloworld/string
http://localhost:8080/helloworld/json
http://localhost:8080/helloworld/page


실행화면

image

image

image

This post is licensed under CC BY 4.0 by the author.