틀린 해석이 있다면 알려주세요
spring document 공식문서 보고 공부하는 중
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping
@Controller
@RestController
기본 클래스를 확장하거나 특정 인터페이스 구현 필요 X
@RestController 는 메타 주석이 추가되어 렌더링할 수 있도록 함
-> @Controller, @ResponseBody 등
1.3.2. Request Mapping
@RequestMapping 주석을 이용하여 컨트롤러 매핑 가능
@RestController
@RequestMapping("/persons")
class PersonController {
@GetMapping("/{id}")
public Person getPerson(@PathVariable Long id) {
// ...
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void add(@RequestBody Person person) {
// ...
}
}
URI 패턴
PathPattern
- ? matches one character
- * matches zero or more characters within a path segment
- ** matches zero or more path segments until the end of the path
- {spring} matches a path segment and captures it as a variable named "spring"
- {spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
- {*spring} matches zero or more path segments until the end of the path and captures it as a variable named "spring"
- "/resources/ima?e.png"- 경로 세그먼트에서 한 문자 일치
- "/resources/*.png"- 경로 세그먼트에서 0개 이상의 문자와 일치
- "/resources/**"- 여러 경로 세그먼트 일치
- "/projects/{project}/versions"- 경로 세그먼트를 일치시키고 변수로 캡처
- "/projects/{project:[a-z]+}/versions"- 정규식으로 변수 일치 및 캡처
@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
// ...
}
예시 적용해보기
호출 -> ~/api/test/2/값
@GetMapping("/api/test/{value1}/{value2})
public test checkTest(@PathVariable Long value1, @PathVariable String value2) {
// value1 = 2
// value2 = 값
}
URI 변수는 적절한 유형으로 변환시켜줌
int. Long, Date 등 지원 가능
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-typeconversion
Web on Servlet Stack
Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, "Spring Web MVC," comes from the name of its source module (spring-webmvc), but it is more commonl
docs.spring.io
++ 5.3 부터
Spring MVC는 더 이상 에 매핑된 컨트롤러 가 에 암시적으로 매핑 .*되는 접미사 패턴 일치를 수행하지 않습니다 . 결과적으로 응답에 대해 요청된 콘텐츠 유형(예: , 등 )을 해석하는 데 경로 확장이 더 이상 사용되지 않습니다 ./person/person.*/person.pdf/person.xml
+ Consumable Media Types
Content-Type 을 요청하여 범위 조정
@PostMapping(path = "/pets", consumes = "application/json")
public void addPet(@RequestBody Pet pet) {
// ...
}
+ Producible Media Types
Accept 를 요청하여 요청 매핑 범위 조정
@GetMapping(path = "/pets/{petId}", produces = "application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId) {
// ...
}
**
미디어유형 상수
MediaTypeAPPLICATION_JSON_VALUE및 와 같이 일반적으로 사용되는 미디어 유형에 대한 상수를 제공합니다 APPLICATION_XML_VALUE.
+ Parameters, headers
흔히 볼 수 있는
parameter conditions 사용 가능
param, hearders 다 가능
@GetMapping(path = "/pets/{petId}", params = "myParam=myValue")
public void findPet(@PathVariable String petId) {
// ...
}
@GetMapping(path = "/pets", headers = "myHeader=myValue")
public void findPet(@PathVariable String petId) {
// ...
}
@GetMapping(value = "/test", headers = HttpHeaders.FROM + "=" + "test")
으로 지정해두었을 경우 -->
ServletRequest 시에
Headers = [From:"test"] < 성공
Headers = [From:"testttt"] < 실패
헷갈리지않아야할 점
url 파라미터 전달 방법은 두가지
1. 쿼리스트링 - 사용하는 어노테이션 @RequestParam
~ test?key1=value1&key2=value2
@GetMapping("/test")
2. RESTful - 사용하는 어노테이션 @PathVariable
/value1/value2
@GetMapping("/test/{value1}/{value2}")
1.10.2. Using Meta-annotations and Composed Annotations
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-meta-annotations
Core Technologies
In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do
docs.spring.io
Explicit Registrations
-> registers a handler method:
@Configuration
public class MyConfig {
@Autowired
public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler)
throws NoSuchMethodException {
RequestMappingInfo info = RequestMappingInfo
.paths("/user/{id}").methods(RequestMethod.GET).build();
Method method = UserHandler.class.getMethod("getUser", Long.class);
mapping.registerMapping(info, handler, method);
}
}
'Web > spring' 카테고리의 다른 글
[Spring framework Web MVC docs] 1.3.4 Model (0) | 2023.02.02 |
---|---|
[Spring framework Web MVC docs] 1.3.3 Handler Methods (0) | 2023.02.01 |
[Spring error] error print properties (0) | 2023.01.25 |
[Spring war Tomcat] (0) | 2023.01.04 |
[Spring Error] Servlet.service() for servlet (0) | 2022.12.28 |