프로젝트/파이널 프로젝트

RESTful Service (1) - 기초

Kiwisae 2022. 11. 22. 17:46

다음과 같은 구조로

사용자를 관리하는 REST API을 생성하여 글을 작성할 수 있도록 예제 프로젝트를 만들어 본다.

 

 

 

 

 

스프링 부트 프로젝트 생성 방법

https://kiwikiwisae.tistory.com/224

 

 

 

 

 

 

application.properties에서 포트번호를 변경했다.

 

server.port=8088

 

 

프로젝트 명을 우클릭해서 Run As > Spring Boot App으로 실행하면 잘 실행된다.

 

 

 

 

Hello World를 출력 시켜보기 위한 컨트롤러를 생성했다.

 

package com.example.restfulwebservice;

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

@RestController
public class HelloWorldController {

//	@RequestMapping(method = RequestMethod.GET, paht="/hello-world")
	@GetMapping(path = "/hello-world")
	public String helloWorld() {
		return "Hello World";
	}

}

 

 

 

 

이것을 자바 빈 형식으로 바꾸어 json 형태로 출력해  본다.

 

package com.example.restfulwebservice;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor	// 생성자 어노테이션
public class HelloWorldBean {
	
	private String message;
	
}
package com.example.restfulwebservice;

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

@RestController
public class HelloWorldController {

	@GetMapping(path = "/hello-world-bean")
	public HelloWorldBean helloWorldBean() {
		return new HelloWorldBean ("Hello World");
	}

}

 

 

 

DispatcherServlet

클라이언트의 모든 요청을 한 곳으로 받아서 처리한다.

요청에 맞는 Handler로 요청을 전달하고, Handler의 실행 결과를 Http Response 형태로 만들어 반환한다.

 

RestController : @Controller + @ResponseBody

View를 갖지 않는 REST Data (JSON / XML) 반환

 

 

 

가변 변수, Path Variable

 

 

 

package com.example.restfulwebservice;

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

@RestController
public class HelloWorldController {

	@GetMapping(path = "/hello-world-bean/path-variable/{name}")
//	public HelloWorldBean helloWorldBean(@PathVariable(value="name") String name) {
	public HelloWorldBean helloWorldBean(@PathVariable String name) {
//		return new HelloWorldBean ("Hello World, " + name);
		return new HelloWorldBean (String.format("Hello World, %s", name));
	}

}