Here, I am going to explain how to add OSGI annotations to custom servlet, the SCR annotations are deprecated in AEM 6.3, so the people who are working on AEM 6.3 must use OSGI annotations, the OSGI annotations are very simple you do not need to remember so many things while defining properties and no need to use PropertiesUtil class to read property values

Step 1: add dependencies


Step 2: import packages

Once the dependencies are added then run “mvn eclipse:eclipse” command in command prompt, finally import below packages in your class file 

import org.osgi.service.component.annotations.*;
import org.osgi.service.metatype.annotations.*;

Step 3: Create a servlet

Here, I am not using separate class to load configuration, if you have so many properties to configure then I would recommend you to create a separate class and load it using @Designate annotation, want to know how to use @Designate annotation then refer my other article OSGI annotations – service
In the activate method inject the configuration class and read the properties 

package com.aem.toolkit.core.servlets;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@Component(immediate = true, service = Servlet.class, property = {
		"sling.servlet.methods=get" },
                 configurationPolicy = ConfigurationPolicy.REQUIRE
@Designate(ocd = DemoServlet.DemoConfiguration.class)
public class DemoServlet extends SlingSafeMethodsServlet {
	private static final long serialVersionUID = 1L;
	private String pagePath;
	Resource resource;
	@ObjectClassDefinition(name = "Demo Servlet")
	public @interface DemoConfiguration {
		@AttributeDefinition(name = "Enter Path", description = "Page or node path")
		String getPath();
	protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
			throws ServletException, IOException {
		ResourceResolver resourceResolver = request.getResourceResolver();
		resource = resourceResolver.resolve(pagePath);
		PrintWriter out = response.getWriter();
	protected void Activate(DemoConfiguration config) {
		pagePath = config.getPath();

Once the code is deployed then go to the configuration manager and configure the page path, you should see the same thing when you hit servlet in the browser

By coderss

Leave a Reply

Your email address will not be published. Required fields are marked *