负载平衡 URL Apache Web 服务器 + Tomcat 7.0.54 上的会话问题

负载平衡 URL Apache Web 服务器 + Tomcat 7.0.54 上的会话问题

我在负载平衡 URL 上遇到了会话问题,会话没有创建,但是当我直接使用 Tomcat URL 时它工作正常。

控制器:

@RequestMapping(value = "/authenticateUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Users> login(@RequestBody LoginParams params, UriComponentsBuilder ucBuilder)  {
    Users user = null;
    try {
        /* Check if user is already logged in*/
        boolean isUserAlreadyLoggedin = false;
        HttpSession httpSession = SessionHandler.getSession();
        if (httpSession.getAttribute("session_user") != null) {
            isUserAlreadyLoggedin = true;
            user = (Users) httpSession.getAttribute("session_user");
        }
        if (!isUserAlreadyLoggedin) {
            // after login related code...
            httpSession.setAttribute("session_user", user);
        }
        return new ResponseEntity<Users>(user, HttpStatus.OK);
    } catch (Exception e) {
        logger.error("Error while authenticating:" + e.getMessage());
    }
 }
}  

我的会话处理程序帮助类:

class SessionHandler{
     public static HttpSession getSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

        HttpSession session = attr.getRequest().getSession(false);
        if (session == null) {
            // Not created yet. Now do so yourself.
            session = attr.getRequest().getSession(true);
        } 
        return session;
    }


 public static boolean isSessionAlive()
 {
      boolean isSessionAlive = false;
        try {

            HttpSession httpSession = SessionHandler.getSession();
            if (httpSession.getAttribute("session_user") != null) {
                isSessionAlive = true;
            }
        }catch(Exception e){
            logger.error("Error in Session handler",e);
        }
        return isSessionAlive;
  }
 }

通过这种方式,我在用户登录时创建会话,并且对于每个请求,我都会检查会话是否通过以下服务创建。

    @RequestMapping(value = "/checkWhetherSessionIsAlive", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> checkWhetherSessionIsAlive(UriComponentsBuilder ucBuilder) {

    boolean isSessionAlive = false;
    try {

        HttpSession httpSession = SessionHandler.getSession();
        if (httpSession.getAttribute("session_user") == null) {
            isSessionAlive = false;
        } else {
            isSessionAlive = true;
        }
    } catch (Exception e) {

    }

    return new ResponseEntity<Boolean>(isSessionAlive, HttpStatus.OK);
}

用户登录后,会话开始创建,用户被重定向到主页,会话立即过期,用户被重定向到登录页面。
总结一下,这个 URL 上没有创建会话:www.application.com/app(f5 负载平衡 --> APache Web 服务器 --> tomcat)

它在 URL 上运行良好:tomcat:8080/AOS/

相关内容