我需要使用漂亮的 URL 向 ServiceTracker 注册 servlet,如 api/item/5
。
在寻找方法时,我发现了 SO answer看起来它应该完全符合我想要做的,但它对我不起作用。当我使用 api/item/*
这样的 URL 注册 servlet 时,要访问它,我必须完全使用该 URL(包括 *
)。它不会将 *
视为通配符。
有没有办法在 OSGi 中获得漂亮的 URL,或者使用 api/item?id=5
样式 URL 是唯一的方法?如果可以的话,如何实现?
这是我的代码:
package hmi;
import hmi.api.get.*;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.util.tracker.ServiceTracker;
public class HMIServiceTracker extends ServiceTracker {
public HMIServiceTracker (BundleContext context) {
super (context, HttpService.class.getName(), null);
}
public Object addingService (ServiceReference reference) {
HttpService httpService = (HttpService) super.addingService (reference);
if (httpService == null) {
return null;
}
try {
httpService.registerServlet ("/hmi/api/get/appliance_list", new ApplianceList(), null, null);
httpService.registerServlet ("/hmi/api/get/appliance/*", new Appliance(), null, null);
httpService.registerResources ("/hmi", "/web", null);
} catch (Exception e) {
e.printStackTrace();
}
return httpService;
}
public void removedService (ServiceReference reference, Object service) {
HttpService httpService = (HttpService) service;
httpService.unregister ("/hmi/api/get/appliance_list");
httpService.unregister ("/hmi/api/get/appliance/*");
httpService.unregister ("/hmi");
super.removedService (reference, service);
}
}
最佳答案
根据 HTTP 服务规范,所有路径均通过前缀匹配进行匹配。因此,您应该从 URL 中删除 /*
。如果您使用 api/item
注册 servlet,那么该 url 下面的所有内容也将触发您的 servlet。
在 servlet 中,使用 HttpServletRequest#getPathInfo()
获取 api/item
之后的所有内容。
关于java - OSGi ServiceTracker 中的漂亮 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26906707/