SpringMVC跳转

SpringMVC从Controller跳转到另一个Controller(转)

https://www.cnblogs.com/wkrbky/p/5962905.html

(1)我在后台一个controller跳转到另一个controller,不需要传递参数,列表页面默认查询所有的

  • 方式一:使用ModelAndView
return new ModelAndView("redirect:/toList");
  • 方式二:返回String
return "redirect:/ toList "; 

response等,这是不带参数的重定向。


(2)列表页面有查询条件,跳转后我的查询条件不能丢掉,这样就需要带参数的了,带参数可以拼接url

  • 方式一:自己手动拼接url

 有个弊端,就是传中文可能会有乱码问题。

new ModelAndView("redirect:/toList?param1="+value1+"&param2="+value2);

所以不能拼接到url上,而是model.AddAttributes("param1","value") ;这样的方式传参过去,同样封装了过去。

  • 方式二:用RedirectAttributes

这个是发现的一个比较好用的一个类,这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。

 这样在toController这个方法中就可以通过获得参数的方式获得这个参数,再传递到页面。过去的url还是和方式一一样的

model.addAttribute("param", value);
return "redirect:/namespace/toController";

(3)带参数不拼接url页面也能拿到值(重点是这个)
 页面取值直接用el表达式就能获得到,这里的原理是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉

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

  @RequestMapping("/index")
    public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
                   throws Exception {
            return "redirect:/main/list";
    }

3. 总结
    最底层还是两种跳转,只是spring又进行了封装而已,所以说跳转的方式其实有很多很多种,你自己也可以封一个,也可以用最原始的response来,也没有问题

 

二.Spring MVC 中的 forward 和 redirect

http://blog.csdn.net/zzjjiandan/article/details/19491253

如果 /hello 就是某个 controller 的映射,我想转发到这个 controller,怎么办?我们可以通过forward 前缀来达到转发到其它资源的目的: 

public String handle() {  
    // return "forward:/hello" => 转发到能够匹配 /hello 的 controller 上  
    // return "hello" => 实际上还是转发,只不过是框架会找到该逻辑视图名对应的 View 并渲染  
    // return "/hello" => 同 return "hello"  
    return "forward:/hello";  
}  

同理,如果我们想重定向到某个资源,我们可以通过 redirect 前缀来达到重定向到其它资源的目的: 

public String handle() {  
    // 重定向到 /hello 资源  
    return "redirect:/hello";  
}  

 

 

 

 

转自:https://www.cnblogs.com/wkrbky/p/5962905.html

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值