基于Jersey使用Session

时间:2024-07-27 12:06:26

原文:https://*.com/questions/909185/jersey-security-and-session-management

方法一、注入HttpServletRequest,然后访问Session

     Session management is the purview of the container in which Jersey is deployed. In most production cases, it will be deployed within a container that performs session management.
The code below is a simple example of a jersey resource that gets the session object and stores values in the session and retrieves them on subsequent calls.
【译】Session属于Jersey运行所属的容器的范畴,在大多数情况下,这个容器都具有session管理功能。下面的代码是一个简单的例子,展示了一个jersey资源方法如何存贮并后续访问session内容。 @Path("/helloworld")
public class HelloWorld { @GET
@Produces("text/plain")
public String hello(@Context HttpServletRequest req) { HttpSession session= req.getSession(true);
Object foo = session.getAttribute("foo");
if (foo!=null) {
System.out.println(foo.toString());
} else {
foo = "bar";
session.setAttribute("foo", "bar");
}
return foo.toString(); }
}

HttpServletRequest getSession

方法二、注入Jersey的SecurityContext,然后访问Session

    Security information of a request is available by injecting a JAX-RS SecurityContext instance using @Context annotation. The injected security context instance provides the equivalent of the functionality available on HttpServletRequest API. The injected security context depends on the actual Jersey application deployment. For example, for a Jersey application deployed in a Servlet container, the Jersey SecurityContext will encapsulate information from a security context retrieved from the Servlet request. In case of a Jersey application deployed on a Grizzly server, the SecurityContext will return information retrieved from the Grizzly request.
【译】http请求的安全信息,可以通过使用annotation @Context 注入JAX-RS的SecurityContext来访问。注入的security context实例提供HttpServletRequest所提供的API,并且基于jersey部署的容器所提供的功能。例如, 基于Servlet容器的Jersey应用,SecurityContext 将会包装从Servlet request获取的信息。如果Jersey应用基于Grizzly server,则SecurityContext将会包装从Grizzly request所获取的信息 示例代码: @Path("basket")
public ShoppingBasketResource get(@Context SecurityContext sc) {
if (sc.isUserInRole("PreferredCustomer") {
return new PreferredCustomerShoppingBasketResource();
} else {
return new ShoppingBasketResource();
}
} 或者,注入SecurityContext 到类实例变量: @Path("resource")
@Singleton
public static class MyResource {
// Jersey will inject proxy of Security Context
@Context
SecurityContext securityContext; @GET
public String getUserPrincipal() {
return securityContext.getUserPrincipal().getName();
}
}

SecurityContext