Spring MVC:如何在会话中存储用户并检索它?

时间:2014-02-21 14:11:48

标签: spring session spring-mvc

我有一个登录页面,用户可以登录到myb应用程序。当用户单击“登录”按钮时,请求由以下控制器处理:

@Controller
@SessionAttributes("user-entity")
public class LoginController extends BaseController {

    @RequestMapping(value="/login", method = RequestMethod.GET)    
    public ModelAndView login(WebRequest webRequest, @ModelAttribute("user") User user) {
        return  new ModelAndView(VIEW_LOGIN_NAME, "user-entity", user);
    }

在上面的代码中,我在会话中添加了用户实体(用户)。但我无法在另一个控制器中检索用户实体:

@Controller
public class ProfileController extends BaseController{  
@RequestMapping(value="/saveprofil", method = RequestMethod.POST)
public ModelAndView saveProfile(@ModelAttribute Profil profil,HttpSession session){
    User user = (User) session.getAttribute("user-entity");

    user.setProfil(profil);
    userServices.createUser(user); 
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("saveProfilSuccess");
    return modelAndView;
} 

用户对象不为null,但所有属性都为null。怎么了?

1 个答案:

答案 0 :(得分:0)

@praacede:尝试使用此代码,您将获得用户

的持久值
public ModelAndView login(WebRequest webRequest, @ModelAttribute("user") User user,HttpSession session{

    session.setAttribute("User-entity",user);
    return new ModelAndView(VIEW_LOGIN_NAME, "user-entity", user); 
}