【问题标题】:Pretty URLs in OSGi ServiceTrackerOSGi ServiceTracker 中的漂亮 URL
【发布时间】:2014-11-13 10:30:50
【问题描述】:

我需要使用漂亮的 URL à la api/item/5 向 ServiceTracker 注册 servlet。

寻找一种方法,我找到了一个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);
    }
}

【问题讨论】:

    标签: java servlets osgi


    【解决方案1】:

    根据 HTTP 服务规范,所有路径都通过前缀匹配进行匹配。因此,您应该从 url 中删除 /*。如果您使用api/item 注册 servlet,那么该 url 下的所有内容也会触发您的 servlet。

    在 servlet 中,使用 HttpServletRequest#getPathInfo() 获取所有内容 api/item

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多