Controller 之间的跳转

在开发中,有时会遇到 controller 之间跳转的状况,并且有时在跳转的时候须要把不一样的参数传递过去,好比从controller a跳转到controller b,再从controller b到前端页面,而且把controller a里的数据好比StringListMap或者对象传递到页面,等等相似状况。结合查找网上的资料以及本身的试验,现总结以下。html

注: 本文实例均在springmvc框架下,其余架构自行调整。前端


1、跳转方式

1. forward

使用返回 String 的方式: return "forward:Xxx.action";java

@RequestMapping("/index")
public String logout(ModelMap model, RedirectAttributes attr) {
	return "forward:test.action";
}

若是使用ModelAndView方式: return new ModelAndView("forward:/tolist");ajax

:此后,都以返回String的方式来叙述。spring

2. redirect

@RequestMapping("/index")
public String logout(ModelMap model, RedirectAttributes attr) {
	return "redirect:test.action";
}

3. forward 和 redirect 比较

**forward**是请求转发,是服务器端行为,至关于一次请求,地址栏的 URL 不会改变。 **redirect**是请求重定向,是客户端行为,至关于两次请求,地址栏的 URL 会改变。安全

2、跳转时数据的传递

1. 方式一:手动拼接 URL

return "redirect:/login.action?name="+ name;

login.action:服务器

@RequestMapping("/login")
	public String login(HttpServletRequest request, ModelMap model, RedirectAttributes attr ) {
       String name = request.getParameter("name");
	   model.addAttribute("name",name);
	   return "login";
	}

而后在login.html接收,用${name}便可。session

拼接url传参的缺点:架构

  • 参数包含中文字符的话,容易出现问题
  • 不能

2. 方式二:RedirectAttributes

RedirectAttributes 是 Spring mvc 3.1 版本以后出来的一个功能,专门用于重定向以后还能带参数跳转的的工具类。 它有两种带参的方式:mvc

第一种:redirectAttributes.addAttributie("prama",value);

redirectAttributes.addAttribute("prama1",value1);
redirectAttributes.addAttribute("prama2",value2);
return:"redirect:/path/list"

这种方法至关于在重定向连接地址追加传递的参数:return:"redirect:/path/list?prama1=value1&prama2=value2(直接追加参数会将传递的参数暴露在连接的地址上,很是的不安全,慎用)

第二种:redirectAttributes.addFlashAttribute("prama",value);

redirectAttributes.addFlashAttribute("prama1",str);
redirectAttributes.addFlashAttribute("prama2",list);
redirectAttributes.addFlashAttribute("prama3",map);
return:"redirect:/path/list.jsp" ;

此方法隐藏了参数,连接地址上不直接暴露,可是能且只能在重定向的页面上获取prama的值。其原理是参数放到了sessionsession在跳转以后立刻移除对象。若是重定向到一个controller,是取不到该prama的值的。


总的来讲,controller之间跳转而后把参数传到前台页面,这种方式实现起来费力不讨好,对于数据传递以及前台页面的接收展现来讲不是很友好,其实能够换成用ajax方式来作,调用后台数据更加灵活而且局部刷新功能也更加友好。But,多一种方式,多一种选择。

相关文章
相关标签/搜索