3

I should pass some information coming with a HTTP header from a request to an EJB and I don't want to add parameters and pass them everywhere I need them. So i used a RequestScoped bean to hold my header values. Is this implementation ok, or do I misunderstand the concept of @RecuestScoped beans?

First I get the headers with an interceptor (Resteasy), and save them into my request scoped bean:

@Provider
@ServerInterceptor
public class SomeInterceptor implements PreProcessInterceptor {

    @Inject
    ApplicationRequestContext appContext;

    @Override
    public ServerResponse preProcess(HttpRequest request, ResourceMethod resourceMethod)
            throws Failure, WebApplicationException {
        List<String> values = request.getHttpHeaders().getRequestHeader("Some-Header");
        if(values != null && values.size() > 0) {
            appContext.setSomeHeader(values.get(0));
        }
        return null;
    }
}

This is the bean:

@RequestScoped
public class ApplicationRequestContext implements Serializable {
    private String someHeader;

    public void setSomeHeader(String someHeader) {
        this.someHeader = someHeader;
    }

    public String getSomeHeader() {
        return someHeader;
    }
}

Then I can access the value (different in every request) from my EJB:

@Stateless
public class CheckInWorkflow {

    @Inject
    ApplicationRequestContext appContext;

    public void someEjbMethod() {
        doSomethingWithThisHeaderValue(appContext.getSomeHeader());
    }
}

Based upon the description of @RequestScoped this should work as expected:

The request scope is active:

  • during the service() method of any servlet in the web application, during the doFilter() method of any servlet filter and when the container calls any ServletRequestListener or AsyncListener,
  • during any Java EE web service invocation,
  • during any remote method invocation of any EJB, during any asynchronous method invocation of any EJB, during any call to an EJB timeout method and
  • during message delivery to any EJB message-driven bean, and during any message delivery to a MessageListener for a JMS topic or queue obtained from the Java EE component environment.
Community
  • 1
  • 1
Mathias Begert
  • 2,354
  • 1
  • 16
  • 26
  • What do your tests say? Does it do what you want? Does it work as you expect it to work? – JB Nizet Dec 28 '15 at 10:43
  • The tests work so far... Also everything I read about CDI seem to correspond with my plan. It is more that I know of @RequestScope'd beans from the (web) context of ManagedBeans, so it feels unnatural to use this in my scenario. – Mathias Begert Dec 28 '15 at 11:38
  • If everything works as expected, and this solutions suits you, and what you're seeing matches with the documentation, you shouldn't be concerned. – JB Nizet Dec 28 '15 at 11:39

1 Answers1

0

The implementation is correct, but it seems like an unnecessary optimization using side effects.

aschoerk
  • 3,333
  • 2
  • 15
  • 29