在前篇文章《OSGi系列 - 开发服务端Web应用之一:Servlet实现》里,我们讲述了如何在OSGi框架下开发Servlet的方法。但是不是所有的Web应用都只有Servlet,还有很多的静态资源,例如HTML、图片、CSS、JS等等,这篇文章我们继续讲述如何在Bundle里面如何包含这些静态资源,然后通过浏览器进行访问。
第一步:打开HelloWorldBundle项目,在src目录下加入下图的这些静态资源:
index.html是一个简单的测试网页,包含对images/equinox.png图片的使用。index.html的内容如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>感谢Equinox</title>
</head>
<body>
你知不知道,我是在Equinox怀抱里诞生的?
<br /><br />
<a href="http://eclipse.org/equinox/"><img src="images/equinox.png" /></a>
</body>
</html>
第二步:修改Activator.java,将静态资源注册到HTTP服务。Activator.java的内容如下:
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<HttpService> 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已经被注册"); http.registerResources("/demo/static", "static", null); System.out.println("/demo/static已经被注册"); } 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已经被卸载"); http.unregister("/demo/static"); System.out.println("/demo/static已经被卸载"); ref = null; } catch(Exception e){ e.printStackTrace(); } } } }
第三步:运行HelloWorldBundle,通过浏览器访问http://localhost/demo/static/index.html。呃,图片出来没有?
本文中的Eclipse项目源码可以通过下面的链接下载: