@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使用其实很相像,只是注解方式简便许多。