」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何從 Spring MVC 控制器操作重新導向到外部 URL?

如何從 Spring MVC 控制器操作重新導向到外部 URL?

發佈於2024-11-20
瀏覽:943

How to Redirect to External URLs from Spring MVC Controller Actions?

從Spring MVC 控制器操作重定向到外部URL

在Spring MVC 中,使用redirect: 前綴重定向到專案內的URL 非常簡單。但是,重定向到外部 URL 可能會很棘手,尤其是在 URL 未指定有效協定的情況下。

考慮以下程式碼,它將重新導向到專案內的 URL:

@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm, 
                          BindingResult result, ModelMap model) 
{
    String redirectUrl = "yahoo.com";
    return "redirect:"   redirectUrl;
}

此程式碼不會重新導向到預期的外部 URL,而是重新導向到具有給定名稱的視圖。若要重新導向至外部 URL,必須在 URL 中包含協議,如下所示:

@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm, 
                              BindingResult result, ModelMap model) 
{
    String redirectUrl = "http://www.yahoo.com";
    return "redirect:"   redirectUrl;
}

但是,此方法需要有有效的協定。要處理沒有有效協議的 URL,有兩種方法:

方法一:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", projectUrl);
    httpServletResponse.setStatus(302);
}

在此方法中,HttpServletResponse物件用於設定位置標頭和狀態碼,強制重定向。

方法2:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:"   projectUrl);
}

此方法採用 ModelAndView 重定向到給定的 URL。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3