본문 바로가기

Backend/SpringBoot

@GetMapping에서 URL 경로 변수로 특수 문자를 처리

URL 경로 변수로 특수 문자를 처리할 때, 슬래시(/)는 기본적으로 경로 구분자로 사용되기 때문에 문제가 발생할 수 있습니다. 인코딩된 슬래시 (%2F)도 경로 구분자로 처리되어, 예기치 않은 400 에러가 발생할 수 있습니다.

 

이를 해결하기 위해 Spring에서 제공하는 방법 중 하나는 UrlPathHelper 설정을 수정하여 슬래시를 인코딩된 형태로 허용하도록 하는 것입니다.

해결 방법:

application.properties 또는 application.yml 파일에서 설정 추가:

spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER

 

이 설정을 추가하면 Spring이 %2F와 같은 인코딩된 슬래시를 경로 변수로 인식할 수 있습니다.

 

spring.mvc.pathmatch.matching-strategy 설정은 Spring Boot 2.6 이상에서 사용 가능합니다. 만약 해당 버전에서 이 옵션을 사용할 수 없다면, 다음과 같은 방식으로 해결할 수 있습니다.

 

UrlPathHelper 설정 수정:

직접 UrlPathHelper를 사용하여 인코딩된 슬래시를 허용하도록 설정할 수 있습니다.

WebMvcConfigurer 사용

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setUrlDecode(false); // 슬래시 인코딩을 허용
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

 

@RequestMapping에서 슬래시 허용

@GetMapping(value = "{keyword:.+}")
public ResponseEntity<?> getKeyword(@PathVariable String keyword) {
    // 처리 로직
    return ResponseEntity.ok(keyword);
}

 

쿼리 파라미터를 사용하는 방법:

만약 경로 변수에서 슬래시 인코딩 문제를 해결하기 어렵다면, URL 경로 대신 쿼리 파라미터로 값을 받을 수 있습니다.

@GetMapping("/search")
public ResponseEntity<?> getKeyword(@RequestParam String keyword) {
    // 처리 로직
    return ResponseEntity.ok(keyword);
}

이 방법은 경로 변수 대신 쿼리 파라미터를 사용하므로, 슬래시 인코딩 문제를 피할 수 있습니다.

 
 

'Backend > SpringBoot' 카테고리의 다른 글

No enum constant com.google.firebase.ErrorCode.UNIMPLEMENTED  (1) 2024.09.06
Communications link failure  (0) 2024.09.06
[Thymeleaf] Resource Versioning  (0) 2022.09.29