【问题标题】:How to Redirect to a URL In a Java/Spring Controller [duplicate]如何重定向到 Java/Spring 控制器中的 URL [重复]
【发布时间】:2020-10-02 03:25:13
【问题描述】:

我正在构建一个 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】:

    你可以使用弹簧RedirectView:

    @GetMapping("/")
    public RedirectView follow() {
        return new RedirectView("www.foo.baa");
    }
    

    【讨论】:

    • 设置 contextrelative=false 正是我所需要的!谢谢
    • 据我所知,默认情况下应该是错误的,但我只将它用于相对路径。很高兴它有帮助!
    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2011-03-19
    • 2012-01-05
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多