1.tologin
<script> function tologin() { var backurl = encodeURIComponent(location.href); location.href = "${contextPath}/cont/tologin.htm?backurl=" + backurl; } </script> @RequestMapping("/tologin.htm") public String tologin(HttpSession session, RequestParameter param) { if (!StringUtils.isBlank(param.getBackurl())) { if (httpSession.getAttribute("NOLOGIN_SHOP_URL") != null) { httpSession.removeAttribute("NOLOGIN_SHOP_URL"); } httpSession.setAttribute("NOLOGIN_SHOP_URL", param.getBackurl()); if (param.getBackurl().endsWith("logout.htm")) httpSession.setAttribute("NOLOGIN_SHOP_URL", ""); } return "web/login"; }
2.login
<script type="text/javascript"> function doLogin() { if (trim($('#username').val()) == "") { showmsg(0, "请输入用户名"); return; } if (trim($('#password').val()) == "") { showmsg(0, "请输入密码"); return; } $.ajax({ url : "${contextPath}/web/login.htm", data : $("#loginForm").serialize(), cache : false, success : function(xmlHttp) { var res = xmlHttp; if (res.errorMessage && res.errorMessage != "") { showmsg(0, res.errorMessage); } else { if (str_isblank(res.status)) { showmsg(1, "登录成功!"); window.setTimeout("window.location='${contextPath}/web/toindex.htm'", 1500); } else { showmsg(1, "登录成功!"); var fromUrl = res.status; location.href = fromUrl; } } } }); } </script> @RequestMapping("/login.htm") @ResponseBody public Response login(Model model, RequestParameter param, InfoUser infoUser) { Response res = new Response(); SessionUser suser = null; if (httpSession.getAttribute(WebConstants.SESSION_USER_KEY) != null) { suser = new SessionUser(); suser = (SessionUser) httpSession.getAttribute(WebConstants.SESSION_USER_KEY); } if (null == suser || StringUtils.isBlank(suser.getUsername())) { // #0: 正常; // #1: 用户名不存在; // #2:密码不正确; Integer ret = webService.loginInfoUser(infoUser); if (ret == 1) { res.setErrorMessage("登录失败,用户名不存在。"); } else if (ret == 2) { res.setErrorMessage("登录失败,密码不正确。"); } else { // 登录成功,写session InfoUser infoUser1 = webService.getInfoUserByName(infoUser.getUsername()); suser = new SessionUser(); suser.setUserid(infoUser1.getUserid()); suser.setUsername(infoUser1.getUsername()); // suser.setPhonenum(infoUser1.getPhonenum()); httpSession.setAttribute(WebConstants.SESSION_USER_KEY, suser); if (httpSession.getAttribute("NOLOGIN_SHOP_URL") != null) { String backurl = (String) httpSession.getAttribute("NOLOGIN_SHOP_URL"); res.setStatus(backurl); httpSession.removeAttribute("NOLOGIN_SHOP_URL"); } } } return res; }
3.logout
<a href="${contextPath}/web/logout.htm" >退出登录</a> @RequestMapping("/logout.htm") public String logout(Model model, RequestParameter param, SessionStatus sessionStatus) { // 清除用户session if (httpSession.getAttribute(WebConstants.SESSION_USER_KEY) != null) { httpSession.removeAttribute(WebConstants.SESSION_USER_KEY); } return "web/index"; }