1. 程式人生 > >springmvc怎麽重定向,從一個controller跳到另一個controller

springmvc怎麽重定向,從一個controller跳到另一個controller

save exce exception pac pro 方式 con .net 它的

第一種情況,不帶參數跳轉:

方法一:使用ModelAndView

    return new ModelAndView("redirect:/toList");

    這樣可以重定向到toList這個方法

方法二:在return後直接,redirect 加上要跳轉的地址,即可以從第一個controller跳到第二個controller,如下圖代碼中方法一

方法三:見藍色框,只要在return後直接加想要跳到的controller的方法名即可,註意,這個方法名不是RequestMapping裏影射的路徑,是controller裏具體的方法,

如圖片中的3和4,走完3後,他會找到4而不是2(2是RequestMapping裏映射的路徑),這個像不像Java方法的重載,如下圖代碼中方法二

技術分享

第二種情況,帶參數跳轉

方法一:直接在後面用?拼接如圖。

技術分享

方法二:用RedirectAttributes,這個是發現的一個比較好用的一個類這裏用它的addAttribute方法,這個實際上重定向過去以後你看url,是它自動給你拼了你的url。

使用方法:attr.addAttribute("param", value);

     return "redirect:/namespace/toController";

這樣在toController這個方法中就可以通過獲得參數的方式獲得這個參數,再傳遞到頁面。過去的url還是和方式一一樣的。

方法三:帶參數不拼接url頁面也能拿到值(重點是這個)

    @RequestMapping("/save")
    public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
                   throws Exception {


        String code =  service.save(form);
        if(code.equals("000")){
            attr.addFlashAttribute("name", form.getName());  
            attr.addFlashAttribute(
"success", "添加成功!"); return "redirect:/index"; }else{ attr.addAttribute("projectName", form.getProjectName()); attr.addAttribute("enviroment", form.getEnviroment()); attr.addFlashAttribute("msg", "添加出錯!錯誤碼為:"+rsp.getCode().getCode()+",錯誤為:"+rsp.getCode().getName()); return "redirect:/maintenance/toAddConfigCenter"; } } [email protected]("/index")   public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr) throws Exception {       return "redirect:/main/list";   } //頁面取值,直接用el表達式就能獲得到,這裏的原理是放到session中,session在跳到頁面後馬上移除對象。所以你刷新一下後這個值就會丟掉。 //3. 最底層還是兩種跳轉,只是spring又進行了封裝而已,所以說跳轉的方式其實有很多很多種,你自己也可以封一個,也可以用最原始的response來,也沒有問題。好了,//就到這兒。 其實也沒有什麽,但是知道了這個就很簡單了,之前沒搞懂,現在搞懂了,和大家分享。有問題的給我留言。

springmvc怎麽重定向,從一個controller跳到另一個controller