深入理解springmvc中controller內方法跳轉forward與redirect

 

使用springmvc的controller的時候,碰到controller內方法的跳轉的問題,記錄下問題以及自己測試的過程。

場景:

業務執行更新操作之後返回列表頁面,列表頁面需默認展示查詢的列表數據,涉及到兩個controller的跳轉。

問題

是使用forward還是redirect跳轉

解決問題
其實使用forward或者redirect都能達到目的,但是有些問題在下面說明。
1、使用forward
a、例如:return "forward:/rest/queryData",實際的效果是在瀏覽器中的url地址還是原地址,存在重複提交的問題,所以forward就不推薦使用了。
b、如果是需要攜帶參數,直接拼接傳遞的參數,例如:return "forward:/rest/queryShopAlisName?phone=xxxxxxx"; 在跳轉的controller中使用參數【@RequestParam("phone") String phone】獲得傳遞的參數值,顯然這樣的方式也是不推薦的。

2、使用redirect
在controller方法的參數中使用RedirectAttributes來
a、不帶參數:
直接使用 return "redirect:/rest/queryShopAlisName";瀏覽器的地址變成跳轉的新地址,避免了重複提交的問題。
b、帶參數的時候:


第一種選擇:直接在url後面拼接參數,使用@RequestParam來取值,不推薦使用


第二種選擇:在controller方法的參數中使用RedirectAttributes來傳遞參數

    @RequestMapping(value = "/checkMember")
    public String checkMember(HttpServletRequest request, RedirectAttributes attr) {
            Member member = null;
        try {
            String phone = request.getParameter("phone");
            ***attr.addAttribute("phone", "xxxx");***
            member = cashierService.checkIsMember(phone);
        } catch (Exception e) {
            logger.error("query member is error happen : " + e);
        }
        return "redirect:/rest/queryShopAlisName";
    }

使用attr.addAttribute來設置值,然後在跳轉的controller中同樣使用@RequestParam來取值,在瀏覽器中同樣是拼接參數的形式,例如:http://localhost:8080/xxxx/xx...,同樣不建議這麼使用。


第三種選擇:使用RedirectAttributes的addFlashAttribute的方法來設置值,原理是在跳轉前將值放入session中,跳轉之後就將值清除掉。瀏覽器的地址不顯示參數的值,推薦使用這種方法來傳值。

attr.addFlashAttribute("phone", "xxxxxxx");

在跳轉的controller的參數中增加@ModelAttribute來取得參數值

@RequestMapping(value = "/queryShopAlisName")
    public String queryShopAlisName(@ModelAttribute("phone")String  phone) {
        ......
        return "";
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章