首页 > 解决方案 > 我无法使用 HttpSession 保存会话属性

问题描述

我正在做一个登录测试应用程序,它以 JSON 格式接收用户名和密码,并将值与数据库进行比较。但由于某种原因,会话没有保存。这是我用于验证用户信息并保存会话的方法:

@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response userLogin(Usuario us , @Context HttpServletRequest rq){
    HttpSession session ;
    //Search for the user with the username provided
    Usuario user = usuarioService.getUsuario(us);
    //Verify that user != to null

    if(user != null){
        //verify that password be the same that provided by the client
        if(user.getPassword().equals(us.getPassword())){
            //Set new Attribute in the session with the user info
            session = rq.getSession(true);
            session.setAttribute("username" , user.getUsername());
            return Response.ok().entity("User:" +user.getUsername() +  "has started session with success " + "Session ID : " +session.getId()).build();
        }
        else{
            return Response.ok().entity("Wrong password, please verify and try again" ).build();
        }
    }else{
        return Response.ok().entity("User : "+ us.getUsername()+ " name not found").build();
    }
}

当我尝试调用保存用户名的会话属性“用户名”时,问题就来了。当我尝试使用检索当前会话 ID 的方法时,我发现它与添加用户名属性时的会话 ID 不同。接下来我用来验证会话信息的方法:

@GET
@Path("/checkSession")
@Produces(MediaType.APPLICATION_JSON)
public Response userLoginCheck(@Context HttpServletRequest rq){
    //Call the current session information
    HttpSession session = rq.getSession(false);
    String msg;
    //Verify if the session is new and return not session available
    if( session == null){
        msg = " Session not available" + session.getId();
        return Response.ok().entity(msg).build();
    }else if(session.getAttribute("username") == null){
        msg = "Has been not possible call the required session SESSION ID : " + session.getId();
        return Response.ok().entity(msg).build();
    }
    else{ //If session != null  & attribute 'username' exist, then call 'username' attribute from the session
        return Response.ok().entity(session.getAttribute("user")).build();
    }
}

在此先感谢您提供解决此问题的任何帮助或想法。

标签: javajax-rsjersey-clienthttpsession

解决方案


推荐阅读