Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

Sling Servlet Context Listener

Avatar

Level 2

Hi All,

 

We are trying to implement the functionality similar to provided by javax.servlet.ServletContextListener.

We need to instantiate the object at the moment of context initialization and then access it from servlets

 

Could somebody help to understand what is the proper way to do that with Sling Servlets?

 

Thanks,

Pavel

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi,

I have never used javax.servlet.ServletContextListener approach, so I can't really suggest around that.

But I have used the static osgi service where I set the value and used it later.



Arun Patidar

View solution in original post

6 Replies

Avatar

Community Advisor

Hi,

Can you explain the use case here, so we can check It can also be implemented other way or sling/osgi/jcr provide anything to fulfill your use case?



Arun Patidar

Avatar

Level 2

The usecase is very general: we need to implement a kind of singleton - an object that collects the information generated during servlet execution and allows to retrieve this information from another servlet.

 

We have custom library supporting this functionality in web container environment, so trying to reuse as much as possible for Sling/AEM deployment scenario.

 

The question appears because of uncertainity of the way of servlet context accessing in order to initialize the "singleton", similar to javax.servlet.ServletContextListener approach.

Avatar

Correct answer by
Community Advisor

Hi,

I have never used javax.servlet.ServletContextListener approach, so I can't really suggest around that.

But I have used the static osgi service where I set the value and used it later.



Arun Patidar

Avatar

Employee Advisor

Servlets are represented as components/services in the OSGI world, and these entities have a clearly defined livecycle.


Your servlet can implement also another service interface, and then the doGet() method could populate data in the service (this service is a singleton!) and you can retrieve this information via the InformationService interface.

@component
public class MyServlet implements SlingSafeMethodsServlet, InformationService {
[...]

Map<String,Object> store;

public void PoJo getInforamation() {
  // collect information from the store
}
public void doGet(...) {
 // implementation
 // and put some data into the store
}