springMVC RedirectAttributes用法

之前看书上说springMVC重定向的时候可以调用RedirectAttributes的addFlushAttribute方法向重定向后的页面传值。

但是实践之后在jsp页面并获取不到值。这是我的代码:

Controller:

@RequestMapping("/test")
	public String test(RedirectAttributes r)
	{
		r.addFlashAttribute("msg","hello");
		return "/fail.jsp";
	}

fail.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${msg }
</body>
</html>
结果并获取不到值......然后百度之,找不到解决方案,去官网看RedirectAttributes的使用说明,并没有页面中如何获取的说明。

只说用到一个FlushMap实现,重定向的时候把属性暂时放在session里面的。

好吧,我估计jsp页面里面有一个flushmap,就把session里面和request里面的attributeNames全打印出来

<%
Enumeration en = request.getParameterNames();
while(en.hasMoreElements())
System.out.println(en.nextElement()); 

%>

输出结果:org.springframework.web.servlet.support.SessionFlashMapManager.FLASH_MAPS

就是你了,通过session.getAttribute("org.springframework.web.servlet.support.SessionFlashMapManager.FLASH_MAPS").getClass().getClassName()获取到是一个List类型的。相同的方法获取到为List<FlashMap>类型,成功了。

下面是jsp最终的代码:

<%
Enumeration en = request.getParameterNames();
while(en.hasMoreElements())
System.out.println(en.nextElement()); 
List<FlashMap> list =(List<FlashMap>)session.getAttribute("org.springframework.web.servlet.support.SessionFlashMapManager.FLASH_MAPS");
FlashMap fm = list.get(0);
String msg=(String)fm.get("msg");

%>
<%=msg %>


猜你喜欢

转载自blog.csdn.net/u012413167/article/details/51637880