Spring Bootを使用して別のURLにリダイレクトする方法

Spring BootではRedirectViewクラスを使用して、別のURLへリダイレクトを行うことができます。

コントローラーのクラスで、リクエストハンドラメソッドを作成し、RedirectViewを使用してリダイレクトビューを作成して、以下のようにリダイレクト先のURLを設定してください。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.view.RedirectView;

@Controller
public class MyController {

    @GetMapping("/redirect")
    public RedirectView redirect() {
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://example.com");
        return redirectView;
    }
}

上記の例では、RedirectViewインスタンスを返すredirectメソッドを作成し、リダイレクト先のURLをhttp://example.comに設定します。これによって、ブラウザは指定されたURLにリダイレクトされます。

コントローラークラスをスキャンするため、起動クラスに@ComponentScanを追加してください。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.example")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

最後に、アプリケーションを起動して /redirect パスにアクセスすると、自動的に http://example.com にリダイレクトされます。

bannerAds