2012-02-16 34 views
36

我想讓我的Spring MVC應用程序重定向到動態URL(由用戶提交)。所以如果我有這樣的代碼,重定向到Spring MVC中的動態URL

@RequestMapping("/redirectToSite") 
protected ModelAndView redirect(
    @RequestParam("redir_url") String redirectUrl, 
    HttpServletRequest request, 
    HttpServletResponse response) 
{ 
    // redirect to redirectUrl here 
    return ? 
} 

我應該寫什麼來重定向到提交的URL?例如http://mySpringMvcApp/redirectToSite?redir_url=http://www.google.com應該重定向到Google。

+4

你嘗試新的ModelAndView(新RedirectView的(的redirectUrl))? – Joe 2012-02-16 13:23:44

+1

@Joe:工作也是如此。好東西。 – Gruber 2012-02-16 13:36:48

+1

不知道你是否考慮過這個問題,但你應該考慮到開放重定向是一種安全反模式,你應該至少在提交的url重定向之前對其進行基本驗證。 參見例如https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet – Kutzi 2014-07-10 08:18:07

回答

77

試試這個:

@RequestMapping("/redirectToSite") 
protected String redirect(@RequestParam("redir_url") String redirectUrl) 
{ 
    return "redirect:" + redirectUrl; 
} 

這是在春季reference documentation16.5.3.2 The redirect: prefix解釋。當然,你可以隨時手動做到這一點:

response.sendRedirect(redirectUrl); 
+1

非常感謝,只是測試它,它的工作。必須將方法返回類型從'ModelAndView'更改爲'String'。 – Gruber 2012-02-16 13:30:45

+0

@ user1035411:的確,我更新了我的答案以反映這一點。 – 2012-02-16 13:32:57

+0

@TomaszNurkiewicz這個方法保留了url中的查詢參數,我該如何擺脫查詢參數並重定向到沒有查詢參數的url? – 2015-11-09 12:08:08

5
@RequestMapping(value="/redirect",method=RequestMethod.GET) 
void homeController(HttpServletResponse http){ 
    try { 
    http.sendRedirect("Your url here!"); 
    } catch (IOException ex) { 

    } 
} 
+0

返回「重定向:http://www.stackoverflow.com」沒有爲我工作。豎起大拇指! – shimatai 2017-03-15 21:36:57