Spring-flash属性(addFlashAttribute)

版权声明:如需转载,请备注链接: https://blog.csdn.net/W_Meng_H/article/details/82183631

应用场景:

用户只能修改自己的创建的任务,Controller层的修改方法要重定向到主页面,在主页面方法中设置错误信息。

解决方案:

1、可以使用session域。

2、使用Spring的flash属性。

本文主要讲一下flash属性:

1、使用RedirectAttributes方法

@RequestMapping(value="/edit/{id}", method = {RequestMethod.GET})
public String Edit(Model model,@PathVariable String id,HttpServletRequest request,RedirectAttributes redirect) {
	//获取当前登陆用户名
	UserDetail onUser = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	String username = onUser.getUsername();
		
	//根据编辑页传入值得到当前任务
	Protask thisProtask = this.protaskService.findOneById(Integer.parseInt(id));
		
	if(onUser.getId() != thisProtask.getUserId()){
		redirect.addFlashAttribute("error", "您不能修改别人创建的任务!");
		return "redirect:/console/protask/list/"+thisProtask.getProject().getId();
	}
}

2、在主页面的方法中,可以直接获得error的值

@RequestMapping(value="/list/{id}")
public String ProjectProtaskList(Model model,@PathVariable String id,HttpServletRequest request){
	Project thisProject=this.projectService.findbyID(id);
	model.addAttribute("thisProject", thisProject);
	request.getSession().setAttribute("project_id",id);
	return "protask/protasklist";
}

3、页面显示

redirect.addFlashAttribute("error", "您不能修改别人创建的任务!");
这种方式能达到重新向带参,而且能隐藏参数,其原理就是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉。

相关学习链接:

https://www.cnblogs.com/zhujiabin/p/4935557.html

https://blog.csdn.net/zhaiax672/article/details/71435604

猜你喜欢

转载自blog.csdn.net/W_Meng_H/article/details/82183631