In the previous articleArticleThe osgi series-one of the Web applications for developing servers: Servlet implementation, describes how to develop servlet methods under the osgi framework. However, not all web applications only have servlets and there are many static resources, such as HTML, images, CSS, and Js, in this article, we will continue to explain how to include these static Resources in the bundle and then access them through a browser.
Step 1: OpenHelloworldbundleProject, inSRCThese static resources added to the directory:
Index.htmlIs a simple test page, includingImages/equinox.pngImage usage. The content of index.html is as follows:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> Do you know that I was born in the arms of equinox?<Br/> <a href = "http://eclipse.org/equinox/"> </a> </body>
Step 2: ModifyActivator. JavaTo register static resources with the HTTP service. The content of activator. Java is as follows:
Package Helloworldbundle; Import Org. osgi. Framework. bundleactivator; Import Org. osgi. Framework. bundlecontext; Import Org. osgi. Framework. serviceevent; Import Org. osgi. Framework. servicelistener; Import Org. osgi. Framework. servicereference; Import Org. osgi. Service. http. httpservice; Public Class Activator Implements Bundleactivator, servicelistener { Private Bundlecontext CTX; Private Servicereference Ref; Public Void Start (bundlecontext context) Throws Exception {CTX = Context; context. addservicelistener ( This , "(Objectclass =" + httpservice. Class . Getname () + ")" );} Public Void Stop (bundlecontext context) Throws Exception {context. removeservicelistener ( This );} Public Void Servicechanged (serviceevent event ){ Switch (Event. GetType ()){ Case Serviceevent. Registered: registerservlet (); Break ; Case Serviceevent. unregistering: unregisterservlet (); Break ;}} Private Void Registerservlet (){ If (Ref = Null ) {Ref = CTX. getservicereference (httpservice. Class ); If (Ref! = Null ){ Try {Httpservice HTTP = CTX. getservice (REF); http. registerservlet ( "/Demo/Hello ", New Helloservlet (CTX ), Null , Null ); System. Out. println ( "/Demo/Hello already registered"); Http. registerresources ( "/Demo/static", "static ", Null ); System. Out. println ( "/Demo/static has been registered" );} Catch (Exception e) {e. printstacktrace ();}}}} Private Void Unregisterservlet (){ If (Ref! = Null ){ Try {Httpservice HTTP = CTX. getservice (REF); http. unregister ( "/Demo/hello" ); System. Out. println ( "/Demo/Hello has been uninstalled" ); Http. unregister ( "/Demo/static" ); System. Out. println ( "/Demo/static has been uninstalled" ); Ref = Null ;} Catch (Exception e) {e. printstacktrace ();}}}}
Step 3: Run helloworldbundle to accessHttp: // localhost/demo/static/index.html. Er, are there any images?
The Eclipse project source code in this article can be downloaded through the following link:
Osgi-HelloWorldBundle2.rar