Many times we get into situation where we have to pass data from-to multiple layers in our application. An example can be application using interceptors. Suppose we have two interceptors in our application, one for login check and second for putting audit information in database. We want to use the User object from first interceptor, into second interceptor.
In RESTEasy based applications, above functionality can be easily implemented using ResteasyProviderFactory instance. ResteasyProviderFactory is enabled by adding a filter in web.xml file using below definition:
<listener> <listener-class> org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap </listener-class> </listener>
Now you can easily get the instance of ResteasyProviderFactory in any class in scope of RESTEasy context. So, to share data between interceptors, you will need to do two steps:
1)Set the data in context map
This context data is set using pushContext() method. This method add the data to a thread local stack defined as:
protected static ThreadLocalStack<Map<Class<?>, Object>> contextualData = new ThreadLocalStack<Map<Class<?>, Object>>();
You need to push data as follows:
User user = new User(); //Set some user attributes //Get registered ResteasyProviderFactory instance ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance(); //Add user into context data map factory.pushContext(User.class, user);
2)Get the data from context map
Getting back the data set in first step is very simple. Use popContextData() method. This context data is thread-local in nature so you do not need to worry about getting wrong data when retrieving in another place in your code.
ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance(); factory.popContextData(User.class);
This way you can use ResteasyProviderFactory to share data between multiple layers in your application.
Happy Learning !!