Tuesday, September 30, 2014

How to register a servlet from a Carbon Component

There are three ways to register a servlet in carbon.
Specifying the servlet details in the web.xml file
Specifying the servlet details in the component.xml file
Registering the servlet with httpService in your component

You can find the sample code in : https://github.com/jsdjayanga/How-to-register-a-servlet-from-a-Carbon-Component

Specifying the servlet details in the web.xml file

Specifying the servlet details in the web.xml file is not recommended when working with the carbon framework, as it has less control over the servlet when it is directly specified in the web.xml

From the remaining two, neither is bad, its totally up to the developer to decide what is best for a given scenario.

Specifying the servlet details in the component.xml file

Specifying the servlet details in the component.xml file is the easiest way of doing this.

In this approach, you need to have your HttpServlet implementation. Then you have to specify the details about your servlet in the component.xml file. Following is how you should specify details


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<component xmlns="http://products.wso2.org/carbon">
   <servlets>
       <servlet id="SampleServlet">
           <servlet-name>sampleServlet</servlet-name>
           <url-pattern>/sampleservlet</url-pattern>
           <display-name>Sample Servlet</display-name>
           <servlet-class>
               org.wso2.carbon.samples.xmlbased.SampleServlet
           </servlet-class>
       </servlet>
   </servlets>
</component>

Once you restart the servlet, with your compiled .jar in the dropins directory (repository/components/dropins), all the request to the  http://ip:port/sampleservlet will be routed to your custom servlet (org.wso2.carbon.samples.xmlbased.SampleServlet).


Registering the servlet with httpService

Registering the servlet with httpService allows dynamically register and unregister services. This allows you to have more control over the availability of the servlet.

In this approach, you need to have your HttpServlet implementation. Then you have to register your servlet with the org.osgi.service.http.HttpService once your bundle get activated.


httpService.registerServlet("/sampledynamicservlet", new SampleDynamicServlet(), null, null);

Then onwards, requests received for the http://ip:port/sampledynamicservlet will be routed to your custom servlet.

In this approach you can unregister your servlet, this cause the http://ip:port/sampledynamicservlet to be unavailable.


httpService.unregister("/sampledynamicservlet");


No comments:

Post a Comment