LoginSignup
8
4

More than 3 years have passed since last update.

Spring boot redirect のdefaultはhttpになることを認識しておく

Last updated at Posted at 2019-06-16

spring bootでredirectする際は、プロトコルがデフォルトでhttpになる。

使用する場合は、プロトコルを意識して使う必要がある。
環境毎(開発、ステージング、本番)でプロトコルが違う場合は、特に注意。
※本来は環境を合わせるべき。

TestContoroller.java
public class TestController {

    @GetMapping("/show")
    public ModelAndView test() {
        return new ModelAndView("redirect:" + "/sample");
    }
}

上記の場合は、
http://localhost/sample になる。
これをapplication.ymlから読み込んでセットしたい場合

TestContoroller.java
@RequiredArgsConstructor
@EnableConfigurationProperties({RedirectUrlProperties.class})
public class TestController {
    private final RedirectUrlProperties redirectUrlProperties;

    @GetMapping("/show")
    public ModelAndView test() {
        return new ModelAndView("redirect:" + buildAdminRedirectUrl("/sample"));
    }

    /*
     * springのredirectはdefaultでhttp
     * 環境ごとのredirectURLを作成するメソッド
     */
    public String buildAdminRedirectUrl(String url) {
        return UriComponentsBuilder.fromUriString(redirectUrlProperties.getUrl() + url).toUriString();
    }
}
application.yml
spring:
  redirect:
    url: https://localhost
RedirectUrlProperties.java
@Getter
@Setter
@ConfigurationProperties(prefix= "spring.redirect")
public class RedirectUrlProperties {
    private String url;
}

ここまでredirectについて記載したが、内部メソッドを叩きたいだけならforwardを使うことも検討する。
ただし、forwardはURLは変わらないのでその辺も含めて適しているか検証が必要。
(redirectは再度リクエストを投げるが、fowardは内部で処理するためリクエストは最初の1回だけ)

以下を参考にさせていただきました。
https://qiita.com/rubytomato@github/items/8d132dec042f695e50f6

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4