@SessionAttribute、@SessionAttributes注解使用、区分与总结

@SessionAttribute、@RequestParam注解在方法参数时(注意不带s)都是用来获取某个值的。如@ModelAttribute是从model中取值,所以必须事先存在;@SessionAttribute同理是从Session中取已经存储的值;@RequestParam用来获取浏览器客户端发来的数据。
而SessionAttributes注解在类上,用来告诉mvc哪些model中的属性要被复制并保存到Session中。
例如:

@Controller
// model中key为"username"的属性会被复制到session中
@SessionAttributes("usernameee") // 以示区分名字任性一点= =
public class MyController{
	@PostMapping("/login")
	public String login(Model model1,String username){
		model1.addAttribute("usernameee", username);
		return "redirect:/myspace"
	}

	@GetMapping("/myspace")
	public String space(@SessionAttribute("usernameee" String username Model model2){ // 此处的model2,与model1已不是同一个了
		model2.addAttribute("usernameee", username);
		return "myspace";
	}		

假设用户在/login处填写了用户密码然后登录,此时login方法负责处理这个post request。
在login方法中将用户名保存在model1中,同时由于**@SessionAttributes(“usernameee”)的存在,usernameee还会被复制到session中,然后login方法结束,model1被销毁,重定向到/myspace。
然后进入space方法,此时的model2不是model1,它里面什么也没有,但是方法参数username我们可以使用注解
@SessionAttribute(“usernameee”)**来从session中获取值。随后space方法结束。
可以发现,这两个session注解和传统的HttpSession使用其实很相像,只是注解方式简便许多。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值