简单的传参我就不再做复述了,这里就说一些我平时不常见的。
一、重定向传参(redirect)
重定向的话很多传参都不能使用了,例如:modelmap.addAttribute;modelAndView.addAttribute.
但是不包括session传参。。。。
(themleaf中取值)
<p th:text="${session.***}"></p>
这个很万能,但是用在局部传参个人感觉没必要。
这时候就有专门为重定向传参开发的一个方法--------------RedirectAttributes
接下来就介绍这个的两个方法:
1).addAttribute
请求 /save 后,跳转至/index,并且会在url拼接 ?param=value1。
@RequestMapping("/save")
public String save(User user, RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("param", "value1");
return "redirect:/index";
}
2). addFlashAttribute(一般用于传递错误信息,刷新页面后就没了)
@RequestMapping("/save")
public String save(User user, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("param", "value1");
return "redirect:/index";
}
请求 /save 后,跳转至 /index,并且可以在 index 对应的模版中通过表达式,比如 jsp 中 jstl 用 ${param},获取返回值。该值其实是保存在 session 中的,并且会在下次重定向请求时删除。
ps:在前台取值的方法就是看你用的什么相应的模板的获取方法,例如themleaf就是使用th:text="${errors}"。
可是其他情况怎么办,如登录重定向,需要传递用户数据?
解决方法:重定向到controller,在controller中将flashMap中的session值取出来,存入新的session。
后台Controller取FlashMap值的具体操作:
方法一:利用httpServletRequest
public String test2(HttpServletRequest request)
{
Map<String,?> map = RequestContextUtils.getInputFlashMap(request);
System.out.println(map.get("test").toString());
return "/test/hello";
}
方法二:利用Spring提供的标签@ModelAttribute
public String test2(@ModelAttribute("test") String str)
{
System.out.println(str);
return "/test/hello";
}
二、.ServletContext属性
ServletContext属性可以再request和session中共享,未来访问ServletContext属性,可以使用application前缀:
<table>
<tr>
<td>context中的attribute</td>
<!-- 检索ServletContext的属性'myContextAttribute' -->
<td th:text="${application.myContextAttribute}">42</td>
</tr>
<tr>
<td>attributes数量:</td>
<!-- 返回attributes的数量 -->
<td th:text="${application.size()}">42</td>
</tr>
<tr th:each="attr : ${application.keySet()}">
<td th:text="${attr}">javax.servlet.context.tempdir</td>
<td th:text="${application.get(attr)}">/tmp</td>
</tr>
</table>