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"
と書くこともできます。
ですが、上記のように書くと他のパラメータを追加する際に困ったことになります。
よほどのことがない限りは避けましょう。