1. 程式人生 > >java web session+cookie實現使用者自動登入

java web session+cookie實現使用者自動登入

      在之前的博文中介紹了專案中防止使用者重複登入的方案及解決非法退出異常的處理方法——監聽瀏覽器關閉事件onbeforeunload,傳送ajax請求到伺服器端執行正常退出程式,以避免使用者被鎖死的情況。然後在實際的測試中發現,有些瀏覽器如火狐是無法監聽到beforeunload事件的,除此以外,在本地和內部測試伺服器都能成功監聽到,部署到專案的電信伺服器上就經常出現無法監聽的情況,這樣在使用時非常影響使用者體驗。因此,考慮使用session和cookie實現使用者自動登入的方案,這樣即使使用者不小心關閉瀏覽器,再次輸入專案地址時能直接登入系統,從而避免了使用者直接關閉瀏覽器後無法再次登入。

首先,在專案預設頁index.jsp,進行重定向操作至logincookie.action。

 <%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	response.sendRedirect(basePath+"logincookie.action");
 %>
       在logincookie.action方法中,獲取當前的cookie和session,如果cookie中存在使用者資訊(username)且session中存放有已登入使用者的資訊(logicId,username,logintime等),則自動跳轉至登入成功頁面(action跳轉),否則進入使用者登入頁面。
public String loginCookie() throws Exception{
		ActionContext acx=ActionContext.getContext();
		 Cookie[] cookies=this.request.getCookies();
		 if(cookies==null){
			 return "login";
		 }
		 
		 HttpServletRequest request = ServletActionContext.getRequest();
		 HttpSession session=request.getSession(false);
		 String sessionId = session.getId();
		 
		 if(ifCookieUserAnddiffSession(sessionId)!=null)
		 {
		   //清理loginUserMap中的使用者資訊
			 username=ifCookieUserAnddiffSession(sessionId).getValue();
			 userlogicId=userManageService.findbyUsername(username).getLogicId();
			 loginUserMap = (Map<Long, String>) acx.getApplication().get(WebConstant.LOGIN_USER_MAP);
			 if(loginUserMap!=null&&loginUserMap.containsKey(userlogicId))
			 {
					loginUserMap.remove(userlogicId);
					session.getServletContext().setAttribute(WebConstant.LOGIN_USER_MAP, loginUserMap);
			 }
			 
		 }
		 
		 //如果session發生變化(過期),進入登入頁面
		 for(Cookie cookie:cookies)
		 {
			 if(cookie.getName().equals("JSESSIONID"))
			 {
				 if(!cookie.getValue().equals(sessionId)){
					 return "login";
				 }
			 }
		 }
		 
		 //自動登入
		 for(Cookie cookie2:cookies)
		 {
			 if(cookie2.getName().equals("user")&&cookie2.getValue()!=null){
				 username=cookie2.getValue();
				 userlogicId=userManageService.findbyUsername(username).getLogicId(); 
			try{
				 if(acx.getSession().get(WebConstant.USER_ID).toString().equals(username))
					 return "mainframe";
				 else {
					 return "login";
				}
			
			   }catch(NullPointerException e)
				 {
				    return "login";	 
				 }
			 }
		 }
		 
		
		 return "login";
	}
	
值得一提的是,當用戶攔截器攔截非法注入等操作的時候,也將跳回index.jsp,這時的sessionId發生變化,需先清除loginUserMap並進入登入頁。

當用戶登入時,新建一個cookie,將username作為一個屬性存放在cookie中,設定cookie的失效時間,然後將sessionId存放到cookie的JsessionId屬性中,新增cookie。

	
						//新增cookie
						Cookie cookie=new Cookie("user",username);
						cookie.setMaxAge(10*60*60);						//設定cookie失效時間
						cookie.setPath("/");
						response.addCookie(cookie);
						
						if(cookies!=null)
						{
							for(Cookie cookie2:cookies)
							{
							   if(cookie2.getName().equals("JSESSIONID"))
								{
							 	  cookie2.setValue(sessionId);
								  cookie2.setMaxAge(10*60*60);
								  cookie2.setPath("/");
								  response.addCookie(cookie2);
								}
							}
						}

   當用戶執行安全退出時,清除cookie。
	   // 清除cookie
			Cookie[] cookies=request.getCookies();
			if(cookies!=null)
			{
				for(Cookie cookie: cookies){
					if(cookie.getValue().equals(username))
					{
						cookie.setValue(null);
						cookie.setMaxAge(0);
						cookie.setPath("/");
						response.addCookie(cookie);
					}
				}
			}
     這樣就能實現session結合cookie的自動登入。