zoukankan      html  css  js  c++  java
  • springMVC controller间跳转 重定向 传递参数的方法

    springMVC controller间跳转 重定向 传递参数的方法

    spring MVC框架controller间跳转,需重定向。有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示。
    常用的方法:
    (1)从一个controller中的方法跳转到另一个controller中的方法不需要传递参数
    方式一:使用ModelAndView
    return new ModelAndView(“redirect:/toList”);
    这样可以重定向到另一个controller的toList这个方法
    方式二:返回String
    return “redirect:/ toList “;
    这是不带参数的重定向。
    ( 2)第二种情况,需要携带参数时参数可以拼接url
    方式一:自己手动拼接url
    new ModelAndView(“redirect:/toList?param1=”+value1+”&param2=”+value2);
    这样有个弊端,就是传中文可能会有乱码问题。
    方式二:用RedirectAttributes,这个是发现的一个比较好用的一个类 , SpringMVC 自己的类
    这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。
    使用方法:
    public String save(RedirectAttributes attr)
    attr.addAttribute(“param”, value);
    return “redirect:/namespace/toController”;
    这样在toController这个方法中就可以通过获得参数的方式获得这个参数,再传递到页面。过去的url还是和方式一
    一样的。
    获得参数的方式:
    request.getParameter(“productActivityId”);
    (3)带参数不拼接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”, “添加出错”);
    return “redirect:/maintenance/toAddConfigCenter”;
    }
    }
    addFlashAttribute() springMVC3中 该方法将信息放到session中,在页面直接用el表达式就可以获得.session在跳到页面后
    马上移除对象。所以你刷新一下后这个值就会丢掉。
    总结
    本质还是两次跳转,spring进行了封装;

  • 相关阅读:
    封装函数通过输入(元素,属性,目标值)改变div样式
    unicode键盘编码表
    js中的索引值
    JavaScript的三大组成部分
    阿望教你用vue写扫雷(超详细哦)
    关于换行以及换行属性
    html中的a标签详解
    利用GitHub Pages + jekyll快速搭建个人博客
    本博客文章转载,请注明出处
    git clone克隆项目太慢,或者直接导致克不下来的解决办法(转载请注明出处)
  • 原文地址:https://www.cnblogs.com/jpfss/p/8651303.html
Copyright © 2011-2022 走看看