Spring MVC ---- RedirectAttributes 使用,请求转发携带参数总结

@RequestMapping("/redirect")
	public String redirectTest(RedirectAttributes attr){
		attr.addAttribute("userName", "root");
		attr.addFlashAttribute("password","123456");
		return "redirect:/book/getbook";
	}



@RequestMapping("/getbook")
	@ResponseBody
	public String getBook(ModelMap map,HttpServletRequest request,@RequestParam("userName") String userName,
			@RequestParam(value = "password",required = false) String password){
		System.out.println("userName : "+map.get("userName"));
		System.out.println("userName1 :" + request.getAttribute("userName"));
		System.out.println("userName2 :" + request.getParameter("userName"));
		System.out.println("userName3 : " + userName);
		
		
		System.out.println("password : "+map.get("password"));
		System.out.println("password1 :" + request.getAttribute("password"));
		System.out.println("password2 :" + request.getParameter("password"));
		System.out.println("password3 : " + password);
		
		return "result";
	}

请求结果

url : http://localhost:9019/book/getbook?userName=root

控制台输出:

userName : null
userName1 :null
userName2 :root
userName3 : root
password : 123456
password1 :null
password2 :null
password3 : null

总结:

请求转发需要携带参数时
1、使用  RedirectAttributes 的 addAttribute()方法设置参数,则参数将直接拼接在转发url后面,然后可以在通过request.getParameter("userName")) 和 直接通过spring mvc配置参数映射接收到参数
2、使用 RedirectAttributes  的 addFlashAttribute()方法设置参数,则参数不会出现在转发url中,然后可以通过modelMap 取出参数


补充:
请求结果页面代码
result welcome in $!{title}; ${userName}; ${password}
结果


 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值