为什么会话属性为空

Why the session attribute is coming as null

A HTML5 UI 连接到后端(REST Jersey 到业务逻辑到 Hibernate 和 DB)。我需要为每个用户登录创建并维护一个会话,直到用户注销。

我不知道如何解决这个问题。

我遵循了这种方法

最初当用户成功登录时,我在会话下设置属性,如下所示

HttpSession session = request.getSession(true);
session.setAttribute("islogged", "islogged");
String value = (String)session.getAttribute("islogged");
System.out.println("****************** The User Logge in Value"+value); 

稍后在另一个页面中,我将通过这种方式检查用户是否已登录

public String checkIfUserLoggedIn() throws JSONException,ClassNotFoundException, SQLException
    {
        HttpSession session = request.getSession();
         String value = (String)session.getAttribute("islogged");

        if(value==null)
        {
            // always its coming here only

        }

    }

我不会依赖 http session。我的方法是在用户登录时服务器 returns 的响应 header 中放置一个 "Authorization" 字段,并要求用户放置完全相同的 header 在每个后续调用中。在此 header 中,您放置有助于服务器找到用户身份的信息 (以 twitter 为例:https://dev.twitter.com/oauth/overview/authorizing-requests)。服务器可以将有关登录用户的信息保存在数据库中,或者您可以在单例中创建一个映射作为您的服务的"authorization gatekeeper"。

我同意 francesco foresti,请不要依赖未经授权的 HTTP 会话。这是不安全的,对您的应用程序来说非常危险。

您是否实施了特定的会话机制? 如果不是,球衣将不会按原样存储会话数据。您将要拨打的每个电话都会给您一个与您不同的会话 ID。 您必须进行身份验证并使用身份验证令牌才能识别您的会话。

  1. 使用 JAX-RS 请务必使用定义的身份验证机制:https://jersey.java.net/documentation/latest/security.html

    @Path("authentication")
    @Singleton
    public static class MyResource {
        // Jersey will inject proxy of Security Context
        @Context
        SecurityContext securityContext;
    
        @GET
        public String getUserPrincipal() {
            return securityContext.getUserPrincipal().getName();
        }
    }
    
  2. 或使用其他框架:Spring、Shiro....等。 我真的更喜欢那个解决方案,因为另一个框架会为你实现很多东西。这样做你会获得很多时间。

请查看官方球衣文档:https://jersey.java.net/documentation/latest/index.html