티스토리 뷰

Spring/Spring REST

Spring : REST - 기초

Korean Eagle 2020. 5. 21. 00:57
728x90

1. REST의 가장 일반적인 사용은 Http 프로토콜을 통해서 이다.

 

2. HTTP 프로토콜의 CRUD를 활용한다. POST(create)/ GET(read)/ PUT(update)/ DELETE(delelet)

 

3. Rest API 테스트나 api 제공 사이트

  1. https://www.jsontest.com/

  2. https://www.programmableweb.com/

  3. https://jsonplaceholder.typicode.com/

 

4. 스프링에서 REST 지원은 Web MVC라이브러리가 같이하고 있다.

  4-1 스프링 webmvc는 @RestController를 지원하고 있고 Rest요청을 처리한다.

  4-2 전 포스트에서 언급한 대로 jackson data bind가 dependency에 있으면 자동변환을 실행한다.

 

5. 세팅하는 방법 - org.apache.maven webapp 1.4를 사용하였고 생성방법은 이전 포스트와 동일하다.

  5-1 의존성 설정

    5-1-1 Spring webmvc, jackson data bind, 기본적인 servlet api가 필요하다.

    5-1-2 이전에는 webmvc를 포함하면서 core, context를 같이 넣었는데, 사실 불필요하다. webmvc만 넣어도 된다.

 

    <!-- spring webmvc -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>5.2.6.RELEASE</version>
	</dependency>
    
    <!-- auto json binding -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.11.0</version>
	</dependency>
    
    <!-- servlet container 지원 -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>4.0.1</version>
		<scope>provided</scope>
	</dependency>

 

  5-2 WebConfig 작성하기

    5-2-1 REST 서버도 web이기 때문에 동일한 형식으로 작성한다.

     5-2-1-1 WebMvcConfigurer를 구현하는데 굳이 안해도 되지만 습관 처럼하는 것도 괜찮다.

 

package pe.pilseong.rest_test.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "pe.pilseong.rest_test")
public class WebConfig implements WebMvcConfigurer {

}

 

    5-2-2 이제 servlet 설정이 필요하다.

 

package pe.pilseong.rest_test.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebDispatcherServlet extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return null;
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class[] { WebConfig.class };
  }

  @Override
  protected String[] getServletMappings() {
    return new String[] { "/" };
  }
}

 

    5-2-3 마지막 Controller 설정이다.

      5-2-3-1 여기서는 간단하게 환영 메시지를 찍어주는 코드이다.

      5-2-3-2 중요한 것은 Controller를 @RestController로 지정하는 것이다.  

 

package pe.pilseong.rest_test.restcontroller;

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

@RestController
public class DemoRestController {
  
  @GetMapping("/hello")
  public String hello() {
    return "Hello pilseong!";
  }
}

 

 

728x90
댓글