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 "";
    }

第一次寫博客來記錄,還請看官多多包涵咯。就這樣結束吧

            </div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM