Jersey 中的会话变量 (Java/JBoss)

Session variables in Jersey (Java/JBoss)

我正在使用 Jersey 和 JBoss 在 Java 中开发 RESTful Web 服务,我需要像在 PHP 中那样存储 "Session variables"。保持客户端的会话但不使用 coockies。

@Context
private UriInfo context;

@Context
private HttpServletRequest httpRequest;

@Path("/firstPage")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String createInstance(@QueryParam("instance") String inst) 
        throws JSONException 
{
    // Here I "declare" the session variable
    HttpSession session = httpRequest.getSession(true);
    session.setAttribute("instance", inst);

    // Creation of the DTO (Data Transfer Object)
    JSONObject innerObj = new JSONObject();
    JSONObject outterObj = new JSONObject();

    innerObj.put("ContactID", "{{Contact.Id}}");
    innerObj.put("EmailAddress", "{{Contact.Field(C_EmailAddress)}}");
    outterObj.put("recordDefinition", innerObj);

    return outterObj.toString();
}

@Path("/secondPage")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String validateInstance(@QueryParam("instance") String inst) 
        throws JSONException 
{
    // Here I "validate" the session variable
    HttpSession session = httpRequest.getSession(true);
    if ((String)session.getAttribute("instance") == inst) {
        JSONObject obj= new JSONObject();

        outterObj.put("status", 200);
        outterObj.put("instance", inst);

        return obj.toString();
    } else {
        JSONObject obj = new JSONObject();
        obj.put("error", 401);
        return obj.toString();
    }
}

这是我所做的,但它没有像我预期的那样工作。有什么解决办法吗?

正如某人已经指出的那样:会话由包含会话 ID 的 cookie 处理,php 使用该 cookie 将客户端连接到会话。

为您java休息服务。根据定义,会话不是休息服务的一部分,甚至不鼓励。

其余架构请参考领域原文档:https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

5.1.3 Stateless

We next add a constraint to the client-server interaction: communication must be stateless in nature, ... ach request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

是否有任何理由反对在请求之间使用创建的数据并将它们附加到第二个请求?