Simple Realization of Java Web Project Login Session Management

scenes to be used:

After the administrator modifies the user authority information, the user needs to be forced to log off and log in again to obtain the latest authority.

Since there is no need to record other user information, I used a static object to manage user-related sessions.

Processing logic

1. Record user session information to a static object when the user logs in.

@RequestMapping(value = "/success")
@ResponseBody
public Result<List<String>> success(HttpServletRequest request, HttpServletResponse response){
    SessionUtil.putSession(request);//管理用户session
    Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    LinkedList<String> roles = new LinkedList<>();
    for (SimpleGrantedAuthority auth : authorities) roles.add(auth.getAuthority());

    final Cookie[] cookies = request.getCookies();
    if (null != cookies) {
        for (Cookie c : cookies) {
            if ("JSESSIONID".equalsIgnoreCase(c.getName())) {
                c.setValue(c.getValue()+";SameSite=None;Secure");
            }
        }
    }
    return new Result<List<String>>(Result.SUCCESS, "登录成功", roles);
}

Realization of login user session management class [Allow one account to log in multiple times]

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

public class SessionUtil {
    private static Map<String,List<HttpSession>> sessionMap = new HashMap<>();

    /**
     * 保存session
     * @param request
     */
    public static void putSession(HttpServletRequest request) {
        String username = request.getParameter("username");
        //获取session
        HttpSession session = request.getSession();
        List<HttpSession> sessionList = sessionMap.get(username);
        if (sessionList==null) {
            sessionList = new ArrayList<>();
            sessionList.add(session);
        } else {
            if (!sessionList.contains(session)){
                sessionList.add(session);
            }
        }
        sessionMap.put(username, SessionList);
        CacheUtil . putStatus ( username , to false ); // initialize the state of the user buffer } / **      * destruction of the session will be removed from the Map      * @param username * / public static void moveSession ( String username) { sessionMap . remove(username);     } /**      * Clear session      * @param username */ public static void destroyedSession ( String username){ List < HttpSession > sessionList =
    

    


     
    
        

    


     
    
        sessionMap.get(username);
        if (sessionList!=null) {
            for (HttpSession session:sessionList) {
                session.invalidate();
            }
            moveSession(username);
        }
    }
    /**
     * 清除所有登录session
     */
    public static void destroyedAllSession(){
        for (String username:sessionMap.keySet()) {
            List<HttpSession> sessionList=sessionMap.get(username);
            for (HttpSession session:sessionList) {
                session.invalidate();
            }
            moveSession(username);
        }
    }
}

 

2. After modifying the user information, perform the user offline operation SessionUtil . destroyedSession ( user .getUsername());

@PostMapping(value = "/update")
@ResponseBody
public Result update(@RequestBody @Validated UserDTO userDTO){
    User user = userService.findUser(userDTO.getId());
    List<Role> userRoleList = new ArrayList<>();
    if (userDTO.getRole().isArray()){
        for (JsonNode roleId:userDTO.getRole()) {
            Role userRole = roleService.getRole(roleId.asInt());
            userRoleList.add(userRole);
        }
    }
    user.setRoles(userRoleList);
    user.setUsername(userDTO.getUsername());
    user.setPassword(userDTO.getPassword());
    user.setEmailAddress(userDTO.getEmailaddress());
    user.setTrueName(userDTO.getTruename());
    user.setProject(userDTO.getProject());
    user.setGroupName(userDTO.getGroupname());
    user.setUpdateTime(new Date());
    userService.editUser(user);
    SessionUtil.destroyedSession(user.getUsername());
    return Result.ok();
}

Guess you like

Origin blog.csdn.net/wangpei930228/article/details/109218492
Recommended