-1
我想寫的方法就像public User getUserFromSession()
,private void setUserInSession(User user)
。我希望當用戶登錄時,它可以保存他的信息。我嘗試但失敗了,我用spring-mvc工作,我想寫getUserFromSession
和setUserInSession
的方法,當我使用另一個控制器時,我可以調用getUserFromSession()
,我可以獲取用戶信息。怎麼做?如何編寫會話方法
我的登錄控制器:
@RequestMapping(value = "/login")
public ModelAndView loginCheck(HttpServletRequest request) {
String userName = request.getParameter("j_username");
String userPwd = request.getParameter("j_password");
boolean isValidUser = populator.loginCheck(userName, userPwd);
if (!isValidUser) {
return new ModelAndView("auth/loginpage", "error", "name or password error!");
} else {
request.setAttribute("j_username", userName);
return new ModelAndView("auth/main");
}
}
我的服務
@Transactional
public boolean loginCheck(String userName, String password) {
boolean rtn = false;
log.debug(userName);
if (!StringUtils.isEmpty(userName)) {
User loginUser = template.lookup(User.class, "login", userName).to(User.class).singleOrNull();
if (loginUser != null) {
String userPassword = loginUser.getPassword();
if (new Md5PasswordEncoder().encodePassword(password, User.SALT).equals(userPassword)) {
rtn = true;
//setUserInSession(loginUser);
//log.debug("====== loginCheck getUserFromSession ===="+getUserFromSession());
}
}
} else {
log.warn("you must input user name");
}
return rtn;
}
public User getUserFromSession();
private void setUserInSession(User user) ;
你爲什麼想自己寫? – chrylis
所以你想要一個方法來包裝'HttpSession session = request.getSession(false); session.setAttribute(「user」,yourUserObject);'另一個包裝'HttpSession session = request.getSession(false); session.getAttribute( 「用戶」);'? –
er..this運作良好,但是當我需要會話時,我應該編寫所有這些,我有很多控制器需要調用它,所以我想抽象它一個類,當我使用它時,只需調用該類, – yang