Spring REST APIでスラッシュを含むパスパラメータ取得方法

Spring REST APIでスラッシュを含むパスパラメータ取得方法

パスパラメータにスラッシュを含む場合の取得方法です。

パスパラメータにスラッシュを含むケースですが、以下のようなイメージです。

http://localhost:8080/test/tmp/a.txt?lang=en

このURLの/tmp/a.txtがパスパラメータになる場合の取得方法です。

正規表現

@RequestMappingで正規表現が使えるので、正規表現を使用してみます。

  @RequestMapping("/test/{resourcepath:^[A-Za-z0-9_@./#&+-]*$}")
  public ResponseEntity<?> handle(@PathVariable String resourcepath) {

このように{変数名:正規表現}とすることでパスパラメータに正規表現を適用する事ができます。

但し上記のように正規表現にスラッシュを含めると意図した通りに動作しません。

ワイルドカード

@RequestMappingで**というワイルドカードが使用できますので、今度はワイルドカードを使用してみます。

ワイルドカードですと、スラッシュを含むパスパラメータを取得することが可能です。

  @RequestMapping("/test/**")
  public ResponseEntity<?> handle(
  HttpServletRequest request,
  @RequestParam(name = "lang", defaultValue = "ja") final String lang) {
  String uri = null;
  uri = request.getRequestURI(); // uri=test/a/b/c
  uri = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString(); // uri=test/a/b/c
  // ...
  // curl -X GET http://localhost:8080/test/hoge/a.jpg?lang=en

HttpServletRequestのgetRequestURI()メソッドでURIが取得できました。

ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString()では、http~から?の手前までが取得ができます。

クエリパラメータもlang変数で取得できます。

参考サイト

Spring 3 RequestMapping: Get path value
Is there a way to get the complete path value after the requestMapping @PathVariable values have been parsed? That is: /...
Spring MVC Getting PathVariables containing dots and slashes
I want to match URLs of the form (where the path will always start with 10. and the rest will be a mix of dots, slashes,...
Using a Slash Character in Spring URLs | Baeldung
Learn several ways to deal with URLs containing slash characters in Spring.

コメント

タイトルとURLをコピーしました