簡體   English   中英

在Spring Controller中重定向的最佳實踐

[英]Best Practice of redirecting in Spring Controller

這里我有控制器方法,例如,

(案例1)一種方法是

@Controller
@requestMapping("main")
Class ControllerClass{

    @RequestMapping("first", method = RequestMethod.POST)
    public String post(Model model){
       //processing  
       return "redirect:second";
    }

    @RequestMapping("second", method = RequestMethod.GET)
    public String post(Model model){
       //processing  
       return "myview";
    }
}

而(案例2)另一種方式是

@Controller
@requestMapping("main")
Class ControllerClass{

    @RequestMapping("first", method = RequestMethod.POST)
    public String post(Model model){
       //processing  
       return "redirect:/main/second";
    }

    @RequestMapping("second", method = RequestMethod.GET)
    public String post(Model model){
       //processing  
       return "myview";
    }
}

兩種方式都可以正常工作,但我想知道哪一種更好,以避免像我最近遇到的未來問題:

當我將請求從另一個控制器轉發到/ main / first時 ,我在使用Case 1的代碼中遇到404錯誤。

根據Spring文檔:

重定向:前綴

雖然RedirectView的使用工作正常,但如果控制器本身創建RedirectView,則無法避免控制器意識到正在發生重定向的事實。 這實際上並不是最理想的,而是將事情過於緊密。 控制器不應該真正關心如何處理響應。 通常,它應該僅根據已注入其中的視圖名稱進行操作。

特殊的重定向:前綴允許您完成此操作。 如果返回的視圖名稱具有前綴redirect:,則UrlBasedViewResolver(以及所有子類)會將此識別為需要重定向的特殊指示。 視圖名稱的其余部分將被視為重定向URL。

凈效果與控制器返回RedirectView的效果相同,但現在控制器本身可以簡單地按照邏輯視圖名稱進行操作。 邏輯視圖名稱(例如redirect:/ myapp / some / resource)將相對於當前Servlet上下文重定向,而重定向等名稱: http//myhost.com/some/arbitrary/path將重定向到絕對URL。

大多數實時企業項目更喜歡在他們使用的所有控制器中使用案例2,因此不同控制器之間的內部調用很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM