利用session来进行系统在线人数统计和重复登录踢人,使用HttpSessionListener

编程

@WebListener

public class SessionListener implements HttpSessionListener {

public static HashMap sessionMap = new HashMap();

public static int online = 0;

@Override

public void sessionCreated(HttpSessionEvent hse) {

online ++;

}

@Override

public void sessionDestroyed(HttpSessionEvent hse) {

HttpSession session = hse.getSession();

DelSession(session);

online --;

}

private static synchronized void DelSession(HttpSession session) {

if (session != null) {

// 删除单一登录中记录的变量

if(session.getAttribute("loginUser") != null){

String username = (String) session.getAttribute("loginUser");

SessionListener.sessionMap.remove(username);

}

}

}

}

2、登录时将sessionId放入map中

if (null != SessionListener.sessionMap.get(user.getDldm())) {

//将第一次登录用户的信息从map中移除

SessionListener.sessionMap.remove(username);

}

//本次登录用户添加到map中

SessionListener.sessionMap.put(user.getDldm(), request.getSession().getId());

3、创建登录拦截器

import com.winning.plat.common.exception.BaseException;

import org.apache.commons.lang.StringUtils;

import org.springframework.stereotype.Component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* @ClassName LoginHandlerInterceptor

* @Description TODO

* @Author WJX

* @Date 2020/6/30 9:40

**/

@Component

public class LoginHandlerInterceptor implements HandlerInterceptor {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

String username = (String) request.getSession().getAttribute("loginUser");

String sessionId = request.getSession().getId();

if(StringUtils.isNotBlank(username)){

if (!StringUtils.equalsIgnoreCase((String) SessionListener.sessionMap.get(username),sessionId)) {

throw new BaseException("该账号在别处登录,请重新登录",505);

}

}

return true;

}

}

4、在webMvcConfig中配置

import com.winning.plat.common.config.AuthorizationInterceptor;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;

import org.springframework.core.Ordered;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

* @Author: nxs@winning.com.cn

*

* @Description: MVC配置

*

* @Date: 2018-06-25 17:05:39

*

*

**/

@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Autowired

private AuthorizationInterceptor authorizationInterceptor;

@Autowired

private LoginHandlerInterceptor loginHandlerInterceptor;

@Override

public void addViewControllers(ViewControllerRegistry registry) {

registry.addViewController("/").setViewName("forward:/login.html");

registry.setOrder(Ordered.HIGHEST_PRECEDENCE);

super.addViewControllers(registry);

}

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(authorizationInterceptor)

// .addPathPatterns() 是配置需要拦截的路径

.addPathPatterns("/**")

// .excludePathPatterns() 用于排除拦截

.excludePathPatterns("/") // 排除127.0.0.1进入登录页

.excludePathPatterns("/login") // 排除127.0.0.1进入登录页

.excludePathPatterns("/queryApp")

.excludePathPatterns("/lib/**") // 排除静态文件

.excludePathPatterns("/js/**")

.excludePathPatterns("/img/**")

.excludePathPatterns("/css/**")

.excludePathPatterns("/*.html") // 排除登录页获取验证码接口

.excludePathPatterns("/*.js") // 排除验证账号密码接口

.excludePathPatterns("/*.css");

registry.addInterceptor(loginHandlerInterceptor)

.addPathPatterns("/**")

.excludePathPatterns("/") // 排除127.0.0.1进入登录页

.excludePathPatterns("/login") // 排除127.0.0.1进入登录页

.excludePathPatterns("/queryApp")

.excludePathPatterns("/lib/**") // 排除静态文件

.excludePathPatterns("/js/**")

.excludePathPatterns("/platcommon/**")

.excludePathPatterns("/img/**")

.excludePathPatterns("/css/**")

.excludePathPatterns("/*.html") // 排除登录页获取验证码接口

.excludePathPatterns("/*.js") // 排除验证账号密码接口

.excludePathPatterns("/*.css");

}

}

5、在启动类上加入注解

@ServletComponentScan

6、登录时将用户名放入session中

session.setAttribute("loginName",username);

7、查询在线人数

/**
     *查询在线人数
     */
    @RequestMapping("/online")
    public Object online() {
        return  "当前在线人数:" + MyHttpSessionListener.online + "人";
    }
8、、退出登录

 /**
     * 退出登录
     */
    @RequestMapping("/Logout")
    public CommonResult Logout( HttpServletRequest request) {
        logger.info("用户退出登录开始!");
        HttpSession session = request.getSession(false);//防止创建Session
        if(session != null){
            session.removeAttribute("loginName");
            session.invalidate();
        }
        logger.info("用户退出登录结束!");
        return new CommonResult(ResultEnum.SUCCESS.getCode(), "退出成功!");
    }

 

以上是 利用session来进行系统在线人数统计和重复登录踢人,使用HttpSessionListener 的全部内容, 来源链接: utcz.com/z/517942.html

回到顶部