本文主要是介绍java web相同用户重复登陆,即用户唯一登录,后登陆挤掉先登录的,设置限制用户同时登陆人数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、web.xml
<listener>
<description>SessionListener</description>
<listener-class>com.fhc.port.socket.SessionListener</listener-class>
</listener>
2、SessionListener监听类
package com.fhc.port.socket;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @Description: session监听器 用户唯一登录,后登陆挤掉先登录的
*/
public class SessionListener implements HttpSessionListener,
HttpSessionAttributeListener {
// log4j
private final static Log log = LogFactory.getLog(SessionListener.class);
// 保存当前登录的所有用户
public static Map<HttpSession, String> loginUserList = new HashMap<HttpSession, String>();
// 用这个作为session中的key
public static String SESSION_LOGIN_NAME = "beenLoginUser";
// session创建时调用这个方法
@Override
public void sessionCreated(HttpSessionEvent arg0) {
}
// Session失效或者过期的时候调用的这个方法,
@Override
public void sessionDestroyed(HttpSessionEvent event) {
try {
loginUserList.remove(event.getSession());
} catch (Exception e) {
e.printStackTrace();
}
}
// 执行setAttribute的时候, 当这个属性本来不存在于Session中时, 调用这个方法.
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
// 如果添加的属性是用户名, 则加入map中
if (se.getName().equals(SESSION_LOGIN_NAME)) {
loginUserList.put(se.getSession(), se.getValue().toString());
}
}
// 当执行removeAttribute时调用的方法
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
// 如果移除的属性是用户名, 则从map中移除
if (se.getName().equals(SESSION_LOGIN_NAME)) {
try {
loginUserList.remove(se.getValue().toString());
} catch (Exception e) {
log.debug(e);
}
}
}
// 当执行setAttribute时 ,如果这个属性已经存在, 覆盖属性的时候, 调用这个方法
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
// 如果改变的属性是用户名, 则跟着改变map
if (se.getName().equals(SESSION_LOGIN_NAME)) {
loginUserList.put(se.getSession(), se.getValue().toString());
}
}
}
3、login登陆控制类
//userLoin登陆函数
@RequestMapping("/userLogin")
public void userLogin(User user,
HttpServletRequest request,
HttpServletResponse response,
HttpSession session) throws UnsupportedEncodingException{
String result = "{\"result\":\"error\"}";
User loginUser = userManager.getUser(user.getUserName(),user.getPassword());
if (null != loginUser)
{
Role role = roleManager.getRole(loginUser.getRoleIndex());
if (null != role){
boolean loginUserMax = false;
loginUserMax = isLogonUser(loginUser.getUserName());
if(loginUserMax){
result = "{\"result\":\"error2\"}";
operationManager.addOperation(1, user.getUserName(), userMachineName, userRemoteIP, 0x00, "登陆失败");
}else{
session.setAttribute("beenLoginUser",loginUser.getUserName());
}
if(!loginUserMax){
result = "{\"result\":\"success\"}";
}
}
}else{
}
PrintWriter out = null;
response.setContentType("application/json");
try {
out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}
finally{
out.close();
}
}
//写一个判断用户是否已经登陆的方法,获取在线登陆的用户人数
public boolean isLogonUser(String userName) {
Set<HttpSession> keys = SessionListener.loginUserList.keySet();
System.out.println("已经存在的session个数:"+keys.size());
if(keys.size() == 2){//限制登陆人数
return true;
}
for (HttpSession key : keys) {
System.out.println("已经存在的session:"+key.getId());
if (SessionListener.loginUserList.get(key).equals(userName)) {
key.invalidate();
}
}
return false;
}
4、前台js
1)login.js
var Login = function () {
return {
//main function to initiate the module
init: function () {
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
loginname: {
required: true
},
password: {
required: true
},
remember: {
required: false
}
},
messages: {
loginname: {
required: "用户名为必填项."
},
password: {
required: "密码为必填项."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
//window.location.href = "/recws/user/userLogin";
userLogin();
}
});
$('.login-form input').keypress(function (e) {
if (e.which == 13) {
if ($('.login-form').validate().form()) {
//window.location.href = "/recws/user/userLogin";
userLogin();
}
return false;
}
});
}
};
}();
function userLogin(){
var userName = $("#userName").attr("value");
var password = $("#password").attr("value");
var remember = $("#remember").attr("value");
//alert("username---login---:"userName);
//alert(password);
//alert(remember);
var user = {
userName:userName,
password:password,
remember: remember
};
$.ajax({
url : "/recws/user/userLogin",
type : "post",
data : user,
async : false,
error : function(data) {
window.location.replace("/recws/");
},
success : function(data) {
if (data.result == "error"){
alert("用户名或密码错误");
window.location.replace("/recws/");
}else if (data.result == "error2"){
alert("登陆用户个数已经达到限制,请注销其他用户");
window.location.replace("/recws/");
}else{
window.location.replace("/recws/recinfo/audioSearch");
}
}
});
}
2)login.jsp
<form class="form-vertical login-form" action="/recws/user/userLogin">
<h3 class="form-title">请登录</h3>
<div class="alert alert-error hide">
<button class="close" data-dismiss="alert"></button>
<span>请输入用户名密码.</span>
</div>
<div class="control-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">用户名</label>
<div class="controls">
<div class="input-icon left">
<i class="icon-user"></i>
<input class="m-wrap placeholder-no-fix" type="text" placeholder="用户名" name="userName" id="userName" value = ""/>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label visible-ie8 visible-ie9">密码</label>
<div class="controls">
<div class="input-icon left">
<i class="icon-lock"></i>
<input class="m-wrap placeholder-no-fix" type="password" placeholder="密码" name="password" id="password" value = ""/>
</div>
</div>
</div>
<div class="form-actions">
<label class="checkbox">
<input type="checkbox" id="remember" name="remember"/> 记住我
</label>
<button type="submit" class="btn green pull-right" οnclick="userLogin1()">
登录 <i class="m-icon-swapright m-icon-white"></i>
</button>
<!-- <input type="submit" class="btn green pull-right m-icon-swapright" value="登录"/> -->
</div>
</form>
这篇关于java web相同用户重复登陆,即用户唯一登录,后登陆挤掉先登录的,设置限制用户同时登陆人数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!