Spring MVC重定向参数传递

Spring MVC重定向参数传递


1.查询参数形式

这种方式直接将参数拼接到url后,发起GET请求;若是对传输数据安全要求比较高则不建议这种方式

/**
 * 测试拼接url传参
 * 
 * @param userId 用户id
 * @return 重定向url
 * @throws Exception
 * @date 2017年9月14日
 */
@RequestMapping("/urlParam")
public String urlParam(@RequestParam("userId") Long userId) throws Exception {
	return "redirect:/user/getUseInfo.do?userId=" + userId;
}
	
/**
 * 获取用户信息
 * 
 * @param userId 用户id
 * @return 重定向url
 * @throws Exception
 * @date 2017年9月14日
 */
@RequestMapping("/getUserInfo")
public String getUserInfo(@RequestParam("userId") Long userId) throws Exception {
	User user = userService.findById(userId);
	...
}


2.url模板

(1).这种方式通过路径参数方式传递,此时userId作为占位符填充到URL模板中;还有一种方式是直接拼接userId,return ".../user/" + userId + ".do"。

按照<<>Spring 实战>中说法,不推荐拼接的方式,当构建URL或SQL查询语句的时候,使用String连接不安全

(2).接收方法通过@PathVariable注解获取路径中的参数

/**
 * 测试URL模板传参
 * 
 * @param model 
 * @param userId 用户id
 * @return
 * @throws Exception
 * @date 2017年9月14日
 */
@RequestMapping("/urlTemplate")
public String urlTemplate(Model model, @RequestParam("userId") Long userId) throws Exception {
	model.addAttribute("userId", userId);
	return "redirect:/user/{userId}.do";
}
	
@RequestMapping("/{userId}")
public String getUserInfo(@PathVariable("userId") Long userId) throws Exception {
	User user = userService.findById(userId);
	...
}

3.使用flash属性

(1).这种方式类似于将参数存放到会话(Session)中,这样在重定向后得以保存之前的数据。Spring也是这么做的,flash属性会一直保存这些数据直到下一次请求,然后才会消失

(2).Spring提供RedirectAttributes设置flash属性,该接口继承了Model,所以也会拥有Model所有功能。具体通过addFlashAttribute()方法设置flash属性

/**
 * 测试flash属性
 * 
 * @param model
 * @param userId 用户id
 * @return 重定向url
 * @throws Exception
 * @date 2017年9月14日
 */
@RequestMapping("/flash")
public String flash(RedirectAttributes model, @RequestParam("userId") Long userId) throws Exception {
	model.addFlashAttribute("userId", userId);
	return "redirect:/user/getUserInfo.do";	
}
	
@RequestMapping("/getUserInfo")
public String getUserInfo(@ModelAttribute("userId") Long userId) throws Exception {
	User user = userService.findById(userId);
	...
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值