Lesson 4: Create a servlet that accesses an OSGi service
About this task
In this lesson, you create a web enabled bundle to contain a servlet that accesses the counter service and displays the results of the service. The servlet accesses the OSGi service by looking up the service through a JNDI InitialContext.
To create the servlet that accesses an OSGi service:
Creating a Web enabled bundle
About this task
Procedure
Adding required packages to the bundle manifest
About this task
Procedure
Creating the implementation to look up an OSGi service
About this task
Procedure
Results
package com.ibm.ws.eba.servlet;
import java.io.IOException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.ws.eba.counter.Counter;
/**
* Servlet implementation class CounterServlet
*/
public class CounterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public CounterServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Counter counter;
try {
InitialContext ic = new InitialContext();
counter = (Counter) ic.lookup("osgi:service/"+Counter.class.getName());
response.getOutputStream().println("counter="+counter.getCount());
}
catch (NamingException e) {
e.printStackTrace(System.out);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Lesson checkpoint
You created the servlet that accesses an OSGi service by looking up the service through a JNDI InitialContext.
In this lesson, you learned about the following topics:
- How to create a web enabled OSGi bundle.
- How to create a servlet.
- How to import bundle dependencies by using Imported Packages.
- How to look up an OSGi service by using InitialContext.