javaweb 判断用户是否重复登入
虾米姐
阅读:794
2021-03-31 21:23:10
评论:0
控制层代码:
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();
}
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。