zoukankan      html  css  js  c++  java
  • Controller 之间的跳转

    Controller 之间的跳转

    spring MVC框架controller间跳转,需重定向。

    有几种情况:

    1. 不带参数跳转
    2. 带参数拼接url形式跳转
    3. 带参数不拼接参数跳转,页面也能显示。

    常用的方法:
    情况一:从一个controller中的方法跳转到另一个controller中的方法不需要传递参数

    • 方式一:使用ModelAndView

      return new ModelAndView(“redirect:/toList”);
      

    ​ 这样可以重定向到另一个controller的toList这个方法.

    • 方式二:返回String

      return “redirect:/ toList “;
      

      这是不带参数的重定向。

    情况二:需要携带参数时参数可以拼接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”);
      

    情况三:带参数不拼接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在跳到页面后马上移除对象,所以你刷新一下后这个值就会丢掉。

  • 相关阅读:
    ActiveX控件开发总结(续)
    Guru of the Week 条款04: 类的构造技巧
    tk
    C++中一个空类的大小为什么是1?
    虚继承
    计算机单位
    Guru of the week:#18 迭代指针.
    kingofark关于学习C++和编程的50个观点
    Guru of the Week 条款06:正确使用const
    Guru of the Week 条款07:编译期的依赖性
  • 原文地址:https://www.cnblogs.com/renxiuxing/p/12747097.html
Copyright © 2011-2022 走看看