2013-10-08 72 views
6

我已經寫了下面的控制器:如何將參數傳遞給在彈簧MVC重定向頁

@RequestMapping(value="/logOut", method = RequestMethod.GET) 
    public String logOut(Model model, RedirectAttributes redirectAttributes) { 
     redirectAttributes.addFlashAttribute("message", "success logout"); 
     System.out.println("/logOut"); 
     return "redirect:home.jsp"; 
    } 

如何改變這種代碼home.jsp頁面上,我可以寫${message}和看"success logout"

+0

你有一個控制器映射來處理'home.jsp'嗎?你的flahs屬性被正確添加。 –

+0

它只是jsp頁面 – gstackoverflow

+0

'redirect'通過'Location'頭向客戶端發回302響應。在你的情況下,'Location'將成爲'home.jsp'的一些URL。你需要有一個處理程序。你做? –

回答

8

當返回值包含redirect:前綴,viewResolver將此識別爲需要重定向的特殊指示。視圖名稱的其餘部分將被視爲重定向網址。客戶會發送一個新的請求到這個redirect URL。因此,您需要將處理程序方法映射到此URL以處理重定向請求。

您可以編寫一個處理方法是這樣來處理重定向請求:

@RequestMapping(value="/home", method = RequestMethod.GET) 
public String showHomePage() { 
    return "home"; 
} 

而且你可以重新寫logOut處理方法是:

@RequestMapping(value="/logOut", method = RequestMethod.POST) 
public String logOut(Model model, RedirectAttributes redirectAttributes) { 
    redirectAttributes.addFlashAttribute("message", "success logout"); 
    System.out.println("/logOut"); 
    return "redirect:/home"; 
} 

編輯:

在應用程序配置文件中,您可以避免使用此條目的showHomePage方法:

<beans xmlns:mvc="http://www.springframework.org/schema/mvc" 
..... 
xsi:schemaLocation="... 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
....> 

<mvc:view-controller path="/home" view-name="home" /> 
.... 
</beans> 

這將轉交/home到被叫home視圖的請求。如果在視圖生成響應之前沒有執行Java控制器邏輯,則此方法適用。

+0

可以我上面的showHomePage方法&? – gstackoverflow

+0

什麼是你的應用程序的'view resolver'配置? –

+0

我犯了錯誤。我想避免showHomePage方法。我的ViewResolver具有通常的構型:類= 「org.springframework.web.servlet.view.InternalResourceViewResolver」> <屬性名= 「前綴」> /WEB-INF /頁/ <屬性名=「後綴「> .jsp gstackoverflow

相關問題