2025. 3. 5. 22:40ㆍSpring Framework/Web on Servlet Stack
📌 Spring에서 URI(Uniform Resource Identifier) 다루기 정리
Spring은 URI를 동적으로 생성, 파싱, 인코딩 및 링크 작성하는 다양한 기능을 제공합니다.
이를 통해 RestTemplate, WebClient, 컨트롤러, 뷰(JSP, Thymeleaf) 등에서 URI를 보다 유연하게 구성할 수 있습니다.
🔹 1️⃣ UriComponents
및 UriComponentsBuilder
Spring에서는 UriComponentsBuilder
를 사용하여 동적으로 URI를 생성할 수 있습니다.
URI 템플릿을 사용하여 변수를 포함한 동적 URI를 쉽게 생성할 수 있습니다.
📍 ✔ 기본 사용법
UriComponents uriComponents = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.encode()
.build();
URI uri = uriComponents.expand("Westin", "123").toUri();
✔ fromUriString("https://example.com/hotels/{hotel}")
→ URI 템플릿 정의
✔ queryParam("q", "{q}")
→ 쿼리 파라미터 추가
✔ encode()
→ URI 인코딩 요청
✔ expand("Westin", "123")
→ 변수 확장 ({hotel} → Westin, {q} → 123
)
✔ toUri()
→ URI 객체 변환
➡️ 결과 URI:
https://example.com/hotels/Westin?q=123
📍 ✔ 더 간단한 방법 (체이닝)
URI uri = UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}?q={q}")
.build("Westin", "123");
➡️ buildAndExpand()
을 직접 사용하면 코드가 더 간결해짐
🔹 2️⃣ UriBuilder
와 UriBuilderFactory
✔ UriComponentsBuilder
는 UriBuilder
인터페이스를 구현하며, URI를 동적으로 구성하는 역할
✔ UriBuilderFactory
는 공유된 설정(기본 URL, 인코딩 옵션 등)을 포함한 URI 빌더를 생성
📍 ✔ RestTemplate
및 WebClient
에서 UriBuilderFactory
설정
RestTemplate에 기본 URL 적용
String baseUrl = "https://example.org";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);
WebClient에 기본 URL 적용
String baseUrl = "https://example.org";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
WebClient client = WebClient.builder().uriBuilderFactory(factory).build();
➡️ baseUrl
을 설정하면 RestTemplate
및 WebClient
의 모든 요청에서 해당 URL을 기본으로 사용 가능
🔹 3️⃣ URI 파싱
Spring은 RFC 3986 표준 파서와 WhatWG URL 파서 두 가지 URI 파싱 방식을 지원합니다.
파서 종류 | 설명 |
---|---|
RFC 3986 파서 (기본값) | 엄격한 표준을 따름 (예외 발생 가능) |
WhatWG URL 파서 | 브라우저 스타일의 URL 처리 (더 유연함) |
✔ 기본적으로 Spring의 RestTemplate
, WebClient
는 RFC 3986을 따름
✔ 유연한 URL 처리가 필요할 경우 WhatWG 파서를 사용하도록 설정 가능
🔹 4️⃣ URI 인코딩
Spring에서는 URI 인코딩 방식을 두 가지로 지원합니다.
인코딩 방식 | 설명 |
---|---|
encode() |
URI 템플릿을 먼저 인코딩하고, URI 변수는 엄격하게 인코딩 |
UriComponents#encode() |
URI 변수를 확장한 후 인코딩 (URI 템플릿은 인코딩되지 않음) |
📍 ✔ encode()
사용 예시
URI uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("New York", "foo+bar")
.toUri();
➡️ 결과 URI:
/hotel%20list/New%20York?q=foo%2Bbar
✔ {city} → "New York"
(공백 %20
으로 인코딩)
✔ {q} → "foo+bar"
(+
기호는 %2B
로 인코딩됨)
🔹 5️⃣ ServletUriComponentsBuilder
를 활용한 상대 URI 생성
✔ 현재 HTTP 요청을 기준으로 상대적인 URI를 생성 가능
✔ HttpServletRequest
정보를 활용하여 기존 URL을 기반으로 새로운 URI 생성
📍 ✔ 기존 요청을 기반으로 새로운 URI 생성
HttpServletRequest request = ...;
URI uri = ServletUriComponentsBuilder.fromRequest(request)
.replaceQueryParam("accountId", "{id}")
.build("123");
➡️ 기존 요청 URI에서 쿼리 파라미터만 변경하여 새로운 URI 생성 가능
🔹 6️⃣ 컨트롤러 메서드로 URI 링크 생성 (MvcUriComponentsBuilder
)
Spring MVC에서는 컨트롤러 메서드의 URL을 동적으로 생성할 수 있습니다.
📍 ✔ MvcUriComponentsBuilder
사용법
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodName(BookingController.class, "getBooking", 21)
.buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
✔ BookingController#getBooking(Long booking)
의 URL을 동적으로 생성
✔ {booking} → 21
, {hotel} → 42
로 자동 확장
🔹 7️⃣ JSP, Thymeleaf에서 링크 생성 (mvcUrl
활용)
뷰 템플릿에서도 Spring MVC 컨트롤러 메서드의 URL을 동적으로 생성 가능
📍 ✔ JSP에서 mvcUrl
활용
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
...
<a href="${s:mvcUrl('PAC#getAddress').arg(0,'US').buildAndExpand('123')}">Get Address</a>
✔ @RequestMapping("/people/{id}/addresses")
컨트롤러의 URL을 동적으로 생성
🔹 Summary 📝
✔ UriComponentsBuilder
→ 동적 URI 생성 및 변수 확장 가능
✔ UriBuilderFactory
→ 기본 URL 및 인코딩 설정 지원
✔ ServletUriComponentsBuilder
→ 현재 요청을 기준으로 새로운 URI 생성 가능
✔ MvcUriComponentsBuilder
→ Spring MVC 컨트롤러 URL을 동적으로 생성
✔ JSP, Thymeleaf에서 mvcUrl
을 활용하여 링크 자동 생성 가능
💡 Spring에서 URI를 다룰 때, 동적으로 유연하게 관리할 수 있는 다양한 도구를 활용할 수 있음! 🚀
출처 : https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-uri-building.html
URI Links :: Spring Framework
In views such as Thymeleaf, FreeMarker, or JSP, you can build links to annotated controllers by referring to the implicitly or explicitly assigned name for each request mapping. Consider the following example: @RequestMapping("/people/{id}/addresses") publ
docs.spring.io
'Spring Framework > Web on Servlet Stack' 카테고리의 다른 글
CORS (2) | 2025.03.05 |
---|---|
Logging (1) | 2025.02.28 |
Multipart Resolver (0) | 2025.02.28 |
View Resolution (0) | 2025.02.28 |
Exceptions (0) | 2025.02.28 |