javaweb 判斷使用者是否重複登入
阿新 • • 發佈:2019-01-31
控制層程式碼:
package com.wlsq.kso.web; import com.wlsq.kso.entity.AccountUser; import com.wlsq.kso.entity.Developer; import com.wlsq.kso.listener.SessionListener; import com.wlsq.kso.service.AccountUserService; import com.wlsq.kso.service.IDeveloperService; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; /** * 使用者登入Controller * * @author zzg * @date 2017-02-27 */ @Controller @RequestMapping(value ="login") public class LoginController { @Autowired private IDeveloperService developerService; @Autowired private AccountUserService accountUserService; //結算管理員退出操作。 @RequestMapping(value ="/logout.html") public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); HttpSession session = request.getSession(false); if (session == null) { // 沒登入,重定向到首頁 String url = response.encodeRedirectURL(request.getContextPath() + "/login.jsp"); response.sendRedirect(url); System.out.println("系統重定向頁面1:"+url); return; } // 從session中移除登入狀態 session.removeAttribute("user"); // 重定向到首頁,URL重寫方式 String url = response.encodeRedirectURL(request.getContextPath() + "/login.jsp"); response.sendRedirect(url); System.out.println("系統重定向頁面2:"+url); } //結算系統管理員登入介面。 @RequestMapping({"/accountUserLogin.html"}) public ModelAndView accountUserLogin(HttpServletRequest request, HttpServletResponse response,@RequestParam String username, @RequestParam String password) { ModelAndView modelAndView = new ModelAndView(); HttpSession session = request.getSession(); // 暫時關閉--驗證碼驗證。 // String reallyCode = (String) session.getAttribute("code"); // if (!code.equalsIgnoreCase(reallyCode)) // { // modelAndView.addObject("error", "驗證碼錯誤"); // modelAndView.setViewName("redirect:/login/accountUserLogin.html"); // } else { Map<String,String> map = new HashMap<String,String>(); map.put("username", username); map.put("password", password); AccountUser acountUser = this.accountUserService.selectAccountUserByUsernamePassword(map); Boolean hasLogin = SessionListener.checkIfHasLogin(acountUser); if (acountUser != null) { //判斷使用者是否重複登入過? if(!hasLogin){ // 手動設定session的有效期為30分鐘 String sessionId = session.getId(); Cookie cookie = new Cookie("JSESSIONID", sessionId); cookie.setMaxAge(60 * 30); cookie.setPath(request.getContextPath()); response.addCookie(cookie); // 如果沒有重複登入,則將該登入的使用者資訊新增入session中 session.setAttribute("user", acountUser); // 比較儲存所有使用者session的靜態變數中,是否含有當前session的鍵值對映,如果含有就刪除 if (SessionListener.containsKey(sessionId)) { SessionListener.removeSession(sessionId); } //把當前使用者封裝的session按,sessionID和session進行鍵值封裝,新增到靜態變數map中。 SessionListener.addUserSession(session); } //返回系統主頁 // if (developer.getUserType().intValue() == 0) // { // modelAndView.setViewName("front_end/application/applications"); // } // else { // modelAndView.setViewName("front_end/application/applications"); // } acountUser.setUpdatedate(new Date()); this.accountUserService.updateByPrimaryKeySelective(acountUser); modelAndView.setViewName("index"); } else { modelAndView.addObject("error", "使用者不存在"); modelAndView.setViewName("redirect:login/accountUserLogin.html"); } //} return modelAndView; } }
監聽器:
package com.wlsq.kso.listener; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.wlsq.kso.entity.AccountUser; public class SessionListener implements HttpSessionListener { // key為sessionId,value為HttpSession,使用static,定義靜態變數,使之程式執行時,一直存在記憶體中。 private static java.util.Map<String, HttpSession> sessionMap = new java.util.concurrent.ConcurrentHashMap<String, HttpSession>(500); /** * HttpSessionListener中的方法,在建立session */ @Override public void sessionCreated(HttpSessionEvent arg0) { // TODO Auto-generated method stub } /** * HttpSessionListener中的方法,回收session時,刪除sessionMap中對應的session */ @Override public void sessionDestroyed(HttpSessionEvent arg0) { // TODO Auto-generated method stub } /** * 得到線上使用者會話集合 */ public static List<HttpSession> getUserSessions() { List<HttpSession> list = new ArrayList<HttpSession>(); Iterator<String> iterator = getSessionMapKeySetIt(); while (iterator.hasNext()) { String key = iterator.next(); HttpSession session = getSessionMap().get(key); list.add(session); } return list; } /** * 得到使用者對應會話map,key為使用者ID,value為會話ID */ public static Map<String, String> getUserSessionMap() { Map<String, String> map = new HashMap<String, String>(); Iterator<String> iter = getSessionMapKeySetIt(); while (iter.hasNext()) { String sessionId = iter.next(); HttpSession session = getSessionMap().get(sessionId); AccountUser user = (AccountUser) session.getAttribute("user"); if (user != null) { map.put(""+user.getId(), sessionId); } } return map; } /** * 移除使用者Session */ public synchronized static void removeUserSession(String userId) { Map<String, String> userSessionMap = getUserSessionMap(); if (userSessionMap.containsKey(userId)) { String sessionId = userSessionMap.get(userId); getSessionMap().get(sessionId).invalidate(); getSessionMap().remove(sessionId); } } /** * 增加使用者到session集合中 */ public static void addUserSession(HttpSession session) { getSessionMap().put(session.getId(), session); } /** * 移除一個session */ public static void removeSession(String sessionID) { getSessionMap().remove(sessionID); } public static boolean containsKey(String key) { return getSessionMap().containsKey(key); } /** * 判斷該使用者是否已重複登入,使用 * 同步方法,只允許一個執行緒進入,才好驗證是否重複登入 * @param user * @return */ public synchronized static boolean checkIfHasLogin(AccountUser user) { Iterator<String> iter = getSessionMapKeySetIt(); while (iter.hasNext()) { String sessionId = iter.next(); HttpSession session = getSessionMap().get(sessionId); AccountUser sessionuser = (AccountUser) session.getAttribute("user"); if (sessionuser != null) { if (sessionuser.getId().equals(user.getId())){ return true; } } } return false; } /** * 獲取線上的sessionMap */ public static Map<String, HttpSession> getSessionMap() { return sessionMap; } /** * 獲取線上sessionMap中的SessionId */ public static Iterator<String> getSessionMapKeySetIt() { return getSessionMap().keySet().iterator(); } }