티스토리 뷰

spring 공부

1. Hello Spring boot !

산도리 2022. 9. 18. 13:10

서버를 배워보고 싶어 시작해보려 한다. 

 

자바를 어느정도 기초를 배운 상태에서 스프링과 자바공부를 병행하려한다..

 

gradle 을 사용하여 Hi Spring boot 를 찍어내 보겠다.

 

 

 

프로젝트를 생성하고 컨트롤러 폴더를 생성, 아래로 api 컨트롤러를 생성한다.

 

이번엔 get 만 해볼 예정.

 

package com.example.hello.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController  // 해당 클래스는 Rest API 를 처리하는 컨트롤러로 등록
@RequestMapping("/api") //RequestMapping URI 를 지정해주는 Annotation
public class ApiController {

    @GetMapping("/hello")  // http://localhost:8080/api/hello 로 매핑
    public String hello(){
        return  "hello spring Boot ! ";
    }

}

 

방법은 이러하다.

 

1. 어노테이션 @RestController 와 @RequestMapping 을 써준다. (주석처리를 통해 의미해서 바란다)

 

2. ApiController 클래스 안에 get 을 할 것이기 때문에 @GetMapping을 사용한다.

 

3. hello 메서드를 통해 hello spring boot ! 를 출력한다. 

 

4. http://localhost:8080/api/hello 로 접속하면 문구가 뜰 것이다.

 

 

 

package com.example.hello.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/get")
public class GetApiController {

    @GetMapping(path = "/hello") //http://localhost:8080/api/get/hello
    public String hello(){
        return "get hello ! ";
    }

    @RequestMapping(path = "/hi" , method = RequestMethod.GET)
    public String hi(){
        return "hi , spring Boot ! ";
    }
}

@RequestMapping 이 URI 경로를 지정해준다면 , 이렇게도 사용할 수 있을 것이다.

 

@GetMapping 혹은 @RequestMapping 둘다 인자로 path 를 지정해줄 수 있으며 @RequestMapping 안에 method 를

 

입력하여 위 코드와 같이 지정해줄 수도 있다.