1. 前端按钮
<img border="0" width="18" height="18" src="<%=basePath %>/style/images/top/user.png" /> <font style="font-size:11px; font-family:Microsoft YaHei"> ${usersession.name } <c:forEach items="${usersession.roles }" var="r"> ${r.name } </c:forEach> </b></font> <%if(session.getAttribute("usersession")!=null){%> <input type="button" value="Log Out" onclick="javascript:logout()" style="color:#2c3e50; font-size:12px;font-weight:bold; border-radius:3px; vertical-align:middle;height:20px; 70px; "/> <%}else {%> <input type="button" value="Log In" onclick="javascript:login()" style="color:#2c3e50; font-size:12px;font-weight:bold; border-radius:3px; vertical-align:middle;height:20px; 70px; "/> <%} %>
2. js函数
<script> function logout(){ $.getJSON("/portal/user/logout?rand="+Math.random(),function(data){ if("success"==data.result){ parent.location.href="/portal/home/index"; } else{ alert("logout failure!"); } }); } function login(){ window.open("/portal/user/loginUI","_parent"); } </script>
3. controller端实现
@RequestMapping("/login") public String login(String loginName, String password, HttpSession session,HttpServletRequest request){ //session.invalidate(); User user = userService.findByLoginNameAndPassword(loginName, password); if(user == null){ request.setAttribute("loginError", "用户名或者密码错误"); return "/userController/loginUI"; } else{ session.setAttribute("usersession", user); } return "/homeController/index"; } @RequestMapping("/logout") public String logout( HttpSession session,HttpServletResponse response){ session.removeAttribute("usersession"); session.invalidate(); JSONObject data = new JSONObject(); try { data.put("result", "success"); } catch (Exception e) { System.out.println(e.getMessage()); } PrintWriter out = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); try { out=response.getWriter(); out.write(data.toString()); out.flush(); out.close(); return null; } catch (IOException e) { e.printStackTrace(); } //return "/userController/logout"; return "/homeController/index"; }