Sling Servlet Context Listener | Community
Skip to main content
December 16, 2022
Solved

Sling Servlet Context Listener

  • December 16, 2022
  • 1 reply
  • 1716 views

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by arunpatidar

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.

1 reply

arunpatidar
Community Advisor
Community Advisor
December 16, 2022

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
pilmenkovAuthor
December 16, 2022

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.

pilmenkovAuthor
December 26, 2022

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.

@8220494 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 }

 


Thank you @joerghoh for the most compact approach