일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- Xcode
- lifecycle
- swift
- Lazy
- git branch strategy
- 보라색오류
- Your app is missing support for the following URL schemes: your_ios_client_id
- ios
- TabBarItems
- spring guide
- schemes
- Structural Identity
- ios login
- bounds이해
- developer
- native개발
- lazy 사용
- view
- xml delegate
- Identity
- Spring
- Quick Help
- consuming a restful web service
- lazy 위험성
- Demystify SwiftUI
- Lifetime of SwiftUI
- Explict Identity
- WWDC21
- frame이해
- 적절한 사용방법
- Today
- Total
Dev_Dylan
[Spring] Study Guide _ Building a RESTful Web Service 맛보기 본문
Spring Guide [REST APIs] 맛보기_1
Point : Local Web Server에 “Hello World” 출력
http://localhost:8080/greeting
Web Application을 Local Server 에서 실행 할 때 접속하는 기본 URL
127.0.0.1
= localhost
동일하다.
Get 요청을 아래 두 URL을 통해 출력함.
http://localhost:8080/greeting
http://localhost:8080/greeting?name=MyName
요약 정리
@GetMapping(””)
이 적용된 method에서 해당 경로 요청이 들어오면 실행하도록 Mapping 해준다.@RequestParam(value = “”, defaultValue=””)
을 매개변수에 작성해주면- 해당 값이 들어오면 자동으로
Mapping
되어 값을 사용할 수 있음. defaultValue
는 값이 없을 때 해당 값으로 대체해준다.http://localhost:8080/greeting
의 경우 defaultValue를 사용하게 되고http://localhost:8080/greeting?name=User
의 경우 User가 json형식으로 들어오게 된다.
- 해당 값이 들어오면 자동으로
@SpringBootApplication
는 아래 3개를 통합해준다.@SpringBootApplication
는 보통 최상의 main에서 실행된다.@Configuration
- Spring IoC컨테이너에 등록하기 위한 어노테이션
@EnableAutoConfiguration
- Spring Boot의 자동 설정 기능을 활성화
- 애플리케이션이 필요한 Bean과 설정을 자동으로 구성,
개발자가 일일이 설정을 작성하지 않도록 도와준다.- 특정 데이터베이스 라이브러리가 포함되면 데이터베이스와 관련된 설정을 자동으로 수행하고, 웹 애플리케이션의 경우 내장 웹 서버를 자동으로 구성하는 등의 역할
@ComponentScan
- Spring이 지정한 패키지 내의 Bean들을 자동으로 검색하여 컨테이너에 등록할 수 있도록 함.
@ComponentScan(basePackages = "com.example")
와 같이 특정 패키지를 스캔할 수 있다.
@GetMapping 은 /greeting을 greeting() 메서드에 맵핑을 해준다.
This controller is concise and simple, but there is plenty going on under the hood. We break it down step by step.
The @GetMapping
annotation ensures that HTTP GET requests to /greeting
are mapped to the greeting()
method.
@RequestParam은 들어온 요청 쿼리의 key = value 를 맵핑해준다. defaultValue를 통해 기본값을 설정 할 수 있다.
@RequestParam
binds the value of the query string parameter name
into the name
parameter of the greeting()
method. If the name
parameter is absent in the request, the defaultValue
of World
is used.
Class에 @RestController 를 달아준다면 내부에서 메서드에 일일이 달아줄 필요없음. + @Controller의역할을 동시에 함.
This code uses Spring @RestController
annotation, which marks the class as a controller where every method returns a domain object instead of a view. It is shorthand for including both @Controller
and @ResponseBody
.
아래와 같이 MappingJackson2HttpMessageConverter 덕분에 json을 맵핑을 통해 곧장 바꿔줄 수 있음
The Greeting
object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you need not do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter
is automatically chosen to convert the Greeting
instance to JSON.
Code
@RestController
public class GreetingController {
private static final String template = "Hello, %s";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
System.out.println("요청이 들어오면 이부분이호출된다.");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
template → 을 통해 name값을 출력해준다.
counter → 요청시마다 계속해서 자동으로 count 값을 올려준다.
public record Greeting(long id, String content) {}
흥미로웠던 부분은 class로 데이터 타입을 정한 것이 아닌 record 타입을 사용한 것.
궁금해서 한번 Good이라는 타입으로 반환 해주었음.
@GetMapping("/good")
public Good getGood(@RequestParam String name) {
System.out.println("here");
return new Good(name, 30);
}
static class Good {
String name;
int age;
// 기본 생성자 추가
public Good() {}
public Good(String name, int age) {
this.name = name;
this.age = age;
}
}
결과는
There was an unexpected error (type=Not Acceptable, status=406).
getter setter가 등록 되어있는 타입이어야 자동으로 json 타입으로 변환되어 반환해준다.
Ref.
'Spring' 카테고리의 다른 글
[Spring] Study Guide _ Consuming a RESTful Web Service 맛보기 (1) | 2024.11.07 |
---|