springmvc的contronller之间携带参数的跳转

来源:互联网 发布:淘宝的售后服务是什么 编辑:程序博客网 时间:2024/05/22 07:04

http://blog.csdn.net/qq_36769100/article/details/70886951


1、首先说一下不带参数的重定向格式:

 

[java] view plain copy


  1.        @RequestMapping(“/controller”)  
  2. public String toController(){  
  3.     return “redirect:otherController.do”;//重定向跳转到其他controller  
  4. }  
  5.   
  6. @RequestMapping(“/otherController”)  
  7. public String toOtherController(String param,Model model){  
  8.     return “success”//第二个controller负责跳转到页面  
  9. }  

这是不带参数的重定向,这种情况一般很少出现。

注意:

这里需要强调一下路径问题,上图实例中跳转到的controller是同一个anction下,路径中貌似是不需要带”/”的。至于跳转到其他action中的controller,路径可能会有不同。

2、重定向带参数的形式(get)

springmvc中有一个RedirectAttributes的类,这个类可以帮我们实现参数的传递:

RedirectAttributes.addAttribute(“参数名1”,参数1);

RedirectAttributes.addAttribute(“参数名2”,参数2);

然后重定向。

上代码:

 

[java] view plain copy


  1. @RequestMapping(“/controller”)  
  2.     public String toController(RedirectAttributes attr){//第一个controller中传入RedirectAttributes参数  
  3.         attr.addAttribute(”param”,“test”);    //封装跳转是需要携带的参数  
  4.         return “redirect:otherController.do”;  
  5.     }  
  6.       
  7.     @RequestMapping(“/otherController”)  
  8.     public String toOtherController(String param,Model model){//这里传入param需要和attr中的key一样  
  9.         System.out.println(”param—–:”+param);//这里输出的为:”param—–:test”  
  10.         model.addAttribute(”param1”, param);  //Model封装参数,携带到前台  
  11.         return “success1”;  
  12.     }  

这种方式相当于系统帮我们在重定向路径的后面携带了参数,类似于:

Return redirect:***.do?参数名1=参数1&参数名2=参数2;

注意:

这种提交方式采用的get,重定向的时候会把参数暴露在网址上,不安全,不建议使用。

2、重定向带参数的形式(隐藏参数)

SpringmvcRedirectAttribute中还有一个addFlashAttribute的方法,这个方法可以实现隐藏信息。

RedirectAttribute.addFlashAttribute(“参数名,参数);

但是使用addFlashAttribute的时候,在目标controller方法的参数列表中需要增加一个注解

@ModelAttribute(“参数名”)String param.

上代码:

[java] view plain copy


  1. @RequestMapping(“/controller2”)  
  2.     public String toController2(RedirectAttributes attr){//依然需要传入RedirectAttributes 参数  
  3.         attr.addFlashAttribute(”param”“test”);  //使用的是addFlashAttribute方法  
  4.         attr.addFlashAttribute(”param1”“test1”);  
  5.         return “redirect:otherController2.do”;  
  6.     }  
  7.       
  8.     @RequestMapping(“/otherController2”)  
  9.     public String totoOtherController2(@ModelAttribute(“param”)String param){//需要添加注解@ModelAttribute  
  10.         System.out.println(”param———-:”+param);//框架会自动帮我们获取  
  11.         return “success2”;  
  12.     }  

通过这种方式,跳转过程中携带的参数,就会被隐藏掉。