users@jersey.java.net

_at_SessionParam or _at_SessionAttribute

From: Erdinc Yilmazel <erdinc_at_yilmazel.com>
Date: Mon, 25 Jan 2010 16:40:36 +0000

Sorry if I am mistaken, but I wonder why there isn't a built-in annotation
for injecting session attributes in Jersey? I know you can inject
HttpServletRequest and access session attributes using it, but that is a lot
of typing.

Writing a @SessionAttribute annotation is achievable by just implementing
three classes...

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SessionAttribute {
   String value();
}

------------------

@Provider
public class SessionParamProvider implements
InjectableProvider<SessionAttribute, Type> {

   @Override
   public ComponentScope getScope() {
      return ComponentScope.PerRequest;
   }

   @Context
   HttpServletRequest requestProxy;

   @Override
   public Injectable<Object> getInjectable(ComponentContext ic,
SessionAttribute a, Type type) {
      return new SessionAttributeInjectable(a.value(), requestProxy);
   }
}

-------------------
public class SessionAttributeInjectable implements Injectable<Object> {
   String attributeName;

   public SessionAttributeInjectable(String attributeName,
HttpServletRequest requestProxy) {
      this.attributeName = attributeName;
      this.request = requestProxy;
   }

   HttpServletRequest request;

   @Override
   public Object getValue() {
      HttpSession session = request.getSession(true);
      return session.getAttribute(attributeName);
   }
}


Erdinc