users@jersey.java.net

Re: [Jersey] _at_SessionParam or _at_SessionAttribute

From: Marc Hadley <Marc.Hadley_at_Sun.COM>
Date: Mon, 25 Jan 2010 11:53:22 -0500

See #6 at:

http://www.prescod.net/rest/mistakes/

While its possible to use sessions via an injected HttpServletRequest, we don't want to make it too easy to do the wrong thing.

Marc.

On Jan 25, 2010, at 11:40 AM, Erdinc Yilmazel wrote:

> 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