登录时进行 session 监听,登录拦截

控制层 根据账号密码设置session

本文地址 https://blog.csdn.net/qq_40791070/article/details/89234805

登录设置session

1.获取从前端传过来的账号 密码,查询该账号密码是否正确,若正确则进行下一步,不正确则直接返回数据 用户名不存在
2.若账号密码正确,则进行判断:

 boolean Result = SessionListener.isOnline(session);

若Result为true ,即该session已在线,则进行销毁session ,并返回数据 账号已登录

//销毁session
request.removeAttribute("sysuser");
request.getSession().invalidate();

若Result为false ,即该session不在线,则将该查出的用户信息设置成session对象,并设置该session对象的有效期,并返回数据 登录成功

boolean istrue = SessionListener.isAlreadyEnter(session, account);
final HttpSession Session = request.getSession();
//将该查出的用户信息设置成session对象,并将该session对象的有效期设置成4个小时
Session.setAttribute("sysuser", sysuser);
Session.setMaxInactiveInterval(4 * 60 * 60);

完整代码

    @RequestMapping(value = "system/CKLoginOfSys.do")
	@ResponseBody
	public String LoginOfSys(final HttpServletRequest request) {
		String account = request.getParameter("account");
		String pwd = request.getParameter("pwd1");
		String data = "用户名不存在";
		try {
		   //先进行登录判断,即账号密码是否正确
			Sysuser sysuser = modelServiceimpl.LoginOfSys(account, pwd);
			//账号密码不正确,即不存在这个用户,用户为空,则返回“用户名不存在”,若存在,则进行下一步判断
			if (sysuser != null) {
			  //获取该电脑的session   每台电脑的session.getID不同 
				final HttpSession session = request.getSession();
				//根据session,判断该是否登陆了,该session与电脑id有关
				// 会在 'public class SessionListener implements HttpSessionListener'中详细讲
				boolean Result = SessionListener.isOnline(session);
				System.out.println("是否在线" + Result);
				if (Result == false) {
				   //用于判断用户是否已经登录以及相应的处理方法     
				   //如果该用户已经登录过,则使上次登录的用户掉线
				   //如果该用户没登录过,直接添加现在的sessionID和account
					boolean istrue = SessionListener.isAlreadyEnter(session, account);
					final HttpSession Session = request.getSession();
					//将该查出的用户信息设置成session对象,并将该session对象的有效期设置成4个小时
					Session.setAttribute("sysuser", sysuser);
					Session.setMaxInactiveInterval(4 * 60 * 60);
					data = "登录成功";  
				} else {
				//若该用户不在线,可能上session对象未销毁,则销毁sysuser对象,销毁session
					request.removeAttribute("sysuser");
					request.getSession().invalidate();
					data = "账号已登录"; 
				}
			}
		} catch (NullPointerException e) {
			data = "用户名不存在";
		}
		return data;
	}

退出销毁session对象

@RequestMapping(value = "system/logout.do")
	public ModelAndView logout(final HttpServletRequest request) {
		request.getSession().invalidate();
		request.removeAttribute("sysuser");
		ModelAndView mv = new ModelAndView("system/login");
		return mv;
	}

Session 监听的实现(判断账号是否登录)

import javax.servlet.http.*; 
import java.util.*;   

public class SessionListener implements HttpSessionListener {
	private static HashMap hUserName = new HashMap();
	//保存sessionID和username的映射       
	/**以下是实现HttpSessionListener中的方法**/ 
	public void sessionCreated(HttpSessionEvent se){ 
	   }  	  
	   
	  public void sessionDestroyed(HttpSessionEvent se)  {  
		       System.out.println("销毁session");
	           hUserName.remove( se.getSession().getId() );       
	  }     
	  /*      
	   * isAlreadyEnter-用于判断用户是否已经登录以及相应的处理方法       
	   * @param sUserName String-登录的用户名称   
	   * @return boolean-该用户是否已经登录过的标志    
	      */   
	       public static boolean isAlreadyEnter(HttpSession session,String account){      
	           boolean flag = false;            
	           if(hUserName.containsValue(account)){  
	               //如果该用户已经登录过,则使上次登录的用户掉线(依据使用户名是否在hUserName中)     
	               flag = true;           
	               //遍历原来的hUserName,删除原用户名对应的sessionID(即删除原来的sessionID和username)        
	               Iterator iter = hUserName.entrySet().iterator();               
	               while (iter.hasNext()) {              
	                   Map.Entry entry = (Map.Entry)iter.next();              
	                   Object key = entry.getKey(); 
	                   System.out.println(key);
	                   Object val = entry.getValue();        
	                   if( ( (String)val ).equals(account) ){          
	                       hUserName.remove(key);                    
	                       }       
	                   }            
	               hUserName.put( session.getId(),account );//添加现在的sessionID和username          
	              // System.out.println("该账号已登录"+"____________"+session.getId());           
	               }   
	              else{  
	                   //如果该用户没登录过,直接添加现在的sessionID和username       
	                   flag = false;               
	                  // ((ActionContext) session).put(LOGIN_INFO, loginfo);  
	                   hUserName.put( session.getId(),account ); 
	                  // System.out.println("该账号未登录"+"____________"+session.getId());       
	                  // System.out.println("hUserName = " + hUserName);     
	                   }           
	           return flag;      
	           }         
	    /*     
	     * isOnline-用于判断用户是否在线      
	    * @param session HttpSession-登录的用户名称       
	   * @return boolean-该用户是否在线的标志      
	    */   
	     public static boolean isOnline(HttpSession session){            
	        boolean flag = true;     
	          if( hUserName.containsKey( session.getId() ) ){     
	              flag = true;         
	      } else{               
	         flag = false;        
	       }            
	       return flag;        
	   }   
	   }   

登录拦截 (只要该session对象不存在,则会被拦截跳转到指定的页面)

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.CBHApp.entity.Sysuser;

public class LoginInterceptor implements HandlerInterceptor{
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub	
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub	
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		try {
			//判断该session是否在线,若不在线则强制重定向到错误页面,若存在,则放过
			boolean Result=SessionListener.isOnline(session);
			if(Result==false){
				System.out.println("拦截后进入登录页面");
				String url=request.getContextPath()+"/error.jsp";
				response.sendRedirect(url);
				return false;
			}else{
				return true;
			}
		} catch (Exception e) {
			String url=request.getContextPath()+"/error.jsp";
			response.sendRedirect(url);
			return false;
		}
	}
}

发布了15 篇原创文章 · 获赞 4 · 访问量 1472

猜你喜欢

转载自blog.csdn.net/qq_40791070/article/details/89234805