utamaro’s blog

誰かの役に立つ情報を発信するブログ

SpringBootでPathVariable付きのリダイレクトをする方法

spring bootを使って、@PathVariableがついているurlにリダイレクトする際の方法について紹介します。

設定は、/redirect/fromにリクエストがあった際に、/redirect/to/{id}へリダイレクトするときの書き方です。

それぞれのurlの仕様について説明します。

/redirect/from

  • postでリクエストを受け付ける。
  • /redirect/to/777へリダイレクトする。

/redirect/to/{id}

  • getでリクエストを受け付ける。
  • redirect/to.htmlを表示する。(サンプルではhtmlまでは載せていません。)
  • idを@PathVariableで取得する。

サンプル

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

@Controller
@RequestMapping(value = "/redirect/")
public class ServicePaymentMethodStatusApiController {

    @RequestMapping(value="/from", method = RequestMethod.POST)
    public String redirectFrom(UriComponentsBuilder uriBuilder) {
        UriComponents uriComponent = uriBuilder
                .path("/redirect/to")
                .pathSegment("777")
                .build();
        // ↓ /redirect/to/777 が作成される。
        String redirectPath = uriComponent.toUri().getPath();
        return "redirect:" + redirectPath;
    }

    @RequestMapping(value="/to/{id}", method = RequestMethod.GET)
    public String redirectTo(@PathVariable("id") int id, UriComponentsBuilder uriBuilder) {
        // thymeleafやjspでレンダリング
        return "redirect/to";
    }
}

UriComponentsBuilderを使ってpathを組み立てています。

このbuilderを使わなくてもreturn "redirect:/redirect/to" + "/777"と書くこともできます。

ですが、上記のように書くと他のパラメータを追加する際に困ったことになります。

よほどのことがない限りは避けましょう。