如何在Java / Spring控制器中重定向到URL

问题描述 投票:0回答:1

我正在构建URL缩短器,并且正在研究“跟踪方法”,例如short.li/?stub=dishpods应该重定向到https://www.amazon.com/gp/product/B07CTQ8THP/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1

如何在控制器中设置此自动重定向?我能找出的最好的方法是打印到控制台,但是我希望它能自动执行。

  @GetMapping("/")
    void follow(@RequestParam String stub) throws IOException, InterruptedException {
        ShortUrl longUrl = repository.findByShortUrl(stub);
        String longUrlString;
        if (longUrl != null) {
            longUrlString = longUrl.getShortUrl();
        } else {
            longUrlString = "https://google.com";
        }

        try {

            URL myurl = new URL(longUrlString);
            con = (HttpURLConnection) myurl.openConnection();

            con.setRequestMethod("GET");

            StringBuilder content;

            try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {

                String line;
                content = new StringBuilder();

                while ((line = in.readLine()) != null) {

                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }

            System.out.println(content.toString());

        } finally {

            con.disconnect();
        }
    }
java spring spring-boot spring-mvc java-11
1个回答
0
投票

您可以使用弹簧RedirectView

@GetMapping("/")
public RedirectView follow() {
    return new RedirectView("www.foo.baa");
}
© www.soinside.com 2019 - 2024. All rights reserved.