spring mvc将model存入到session中去

    今天需要针对预览功能将参数通过window.open(url+参数)的方式请求后台方法,进行页面跳转,然而当参数太大时,通过url的方式会导致请求参数过长而失败。所以只能改用post方式,将参数以bean或者requestbosy的方式传递给controller,但是这种方会使原来能自动跳转的url不跳转,目前还没找到原因。通过redirect的方式会导致塞到model的参数无法获取,因此需要将model参数存入到session中去。参考了以下两篇原文,供大家参考。

 

原文参考:http://blog.csdn.net/u012325167/article/details/52426523

              https://zhidao.baidu.com/question/476889704.html

今天遇到一个需求,在用户登陆之后,需要将其登陆状态保存到Session中。

我的逻辑是:用户登陆——用户登陆相关的Controller——验证完成之后,重定向到首页相关的Controller,进行相关信息的展示

在这个过程中,我在用户登陆成功后,利用RedirectAttributes将用户信息存入到其中,然后重定向到首页相关的Controller。但是之后遇到了一个问题:在展示数据的时候,第一次展示时,用户信息是存在的(也就是在刚刚重定向过来的时候),但如果这时候刷新页面,用户信息就消失了。这是因为我只把用户信息存在了RedirectAttributes中,RedirectAttributes之所以能在第一次显示,其实是利用了Session,它会在第一次跳转过来之后取到用户信息,然后再将Session中的用户信息删除掉,这就是刷新页面后信息消失的原因。

为了解决这个问题,我用到了@SessionAttributes。

方法是:

将@SessionAttributes注解到【首页相关的Controller】上,这样做的目的是:在用户验证完成后,重定向到【首页相关的Controller】时,将存放在Model中的指定内容存入Session中,这样以后的地方需要用到该数据时可以直接从Session中获取。

简单示例:

用户登陆的Controller中的验证方法:


@RequestMapping(value = "/login", method = {RequestMethod.POST})
public String login(String username, String password, RedirectAttributes model) {
   if ("xxx".equals(username) && "xxx".equals(password)) {
       model.addFlashAttribute("isAdmin", true);
       return "redirect:/";
   } else {
       model.addFlashAttribute("errorMsg", "用户名或密码错误!");
       return "redirect:/backend";
   }
}

 

在该Controller上注解@SessionAttributes,使得在调用该Controller时,将Model中的数据存入Session


@Controller
@RequestMapping("/")
@SessionAttributes("isAdmin")
public class IndexController extends BasicController {

    //....

}

大功告成

posted @ 2016-11-16 17:48  flydico  阅读(4394)  评论(0编辑  收藏  举报