2014-12-04 3 views
1

У меня проблема. Я хочу использовать OSGi для веб-сайта. Я довольно новичок в OSGi, но я прочитал основы и хочу использовать фреймворк Equinox. Для этого я прочитал Краткое руководство от http://eclipse.org/equinox/ и купил и прочитал книгу «OSGi и равноденствие - создание высоко модульных систем Java»OSGi в веб-контейнере - запрошенный ресурс недоступен (файл JSP)

Но вернемся к моей проблеме. Я загрузил bridge.war с сайта equinox и createt первым пакетом с сервлетом. Активатор выглядеть следующим образом:

public void start(BundleContext bundleContext) throws Exception { 
    Activator.context = bundleContext; 
    httpServiceTracker = new HttpServiceTracker(context); 
    httpServiceTracker.open(); 
} 


public void stop(BundleContext bundleContext) throws Exception { 
    Activator.context = null; 
    httpServiceTracker.close(); 
    httpServiceTracker = null; 
} 

private class HttpServiceTracker extends ServiceTracker { 

public HttpServiceTracker(BundleContext context) { 
    super(context, HttpService.class.getName(), null); 
} 

public Object addingService(ServiceReference reference) { 
    HttpService httpService = (HttpService) context.getService(reference); 
    try { 
    httpService.registerServlet("/index", new StartServlet(), null, null); //$NON-NLS-1$ 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
    return httpService; 
} 

public void removedService(ServiceReference reference, Object service) { 
    HttpService httpService = (HttpService) service; 
    httpService.unregister("/index"); //$NON-NLS-1$ 
    super.removedService(reference, service); 
} 
} 

И мой Servlet выглядеть следующим образом:

защищен недействительным doGet (HttpServletRequest запрос, HttpServletResponse ответ) бросает ServletException, IOException { performTask (запрос, ответ); }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 
    IOException { 
performTask(request, response); 
} 

private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, 
    IOException { 
RequestDispatcher RequestDispatcherview = request.getRequestDispatcher("test.jsp"); 
RequestDispatcherview.forward(request, response); 
} 

СПЯ Файл находится в папке/WebContent/который находится в Bundle. Если я разворачивать сверток в bridge.war и попытаться открыть сайт в браузере, я всегда получаю следующее:

enter image description here

Я не знаю, как я могу настроить мой сервлет или мой Activator, что они найдут файл jsp. Я попытался переместить JSP-файл в bridge.war, но это не помогает мне предотвратить эту проблему.

Я думаю, мне нужно зарегистрировать файл jsp где угодно (возможно, с httpService.registerResources(arg0, arg1, arg2);), но я не знаю, как я это делаю правильно.

Надеюсь, вы можете мне помочь.

+0

Вы зарегистрировали свой сервлет в контексте «/ index», разве у вас нет «индекса» в вашем URL-адресе? –

+0

Если я открою http: // localhost: 8080/bridge/index, сервлет будет активирован, а в сервлете я попытаюсь отправить запрос на test.jsp, но сервлет не сможет найти файл jsp. – Baalthasarr

+0

Как обстоит дело, разверните веб-приложение в контейнере OSGi. Либо создайте собственную настройку пакетов, либо используйте контейнер OSGi, такой как Apache Karaf. –

ответ

1

Я, наконец, решил свою проблему. Я использовал точки расширения. Вот мой plugin.xml:

<plugin> 
    <extension point="org.eclipse.equinox.http.registry.httpcontexts"> 
     <httpcontext id="html"> 
      <resource-mapping path="/WebContent/static"/> 
     </httpcontext> 
    </extension> 
    <extension point="org.eclipse.equinox.http.registry.resources"> 
     <resource alias="/webApp" httpcontextId="html"/> 
    </extension> 

    <extension point="org.eclipse.equinox.http.registry.httpcontexts"> 
     <httpcontext id="jsp"> 
      <resource-mapping path="/WebContent/dynamic"/> 
     </httpcontext> 
    </extension> 
    <extension point="org.eclipse.equinox.http.registry.servlets"> 
     <servlet alias="/webApp/*.jsp" class="org.eclipse.equinox.jsp.jasper.registry.JSPFactory" httpcontextId="jsp"/> 
     <servlet alias="/webApp/Login" class="webfiles.servlets.Login"/> 
    </extension> 
</plugin> 

Мои пуска и останова методы в Активатор ищут так:

Начало:

@Override 
public void start(BundleContext bundleContext) throws Exception { 
    super.start(bundleContext); 
    Activator.context = bundleContext; 

    Bundle jettBundle = Platform.getBundle("org.eclips.equinox.http.jetty"); 
    Bundle httpRegistryBundle = Platform.getBundle("org.eclipse.equinox.http.registry"); 
    try { 
     jettBundle.start(); 
     httpRegistryBundle.start(); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 
} 

Стоп:

@Override 
public void stop(BundleContext bundleContext) throws Exception { 
    super.stop(bundleContext); 
    Activator.context = null; 

    Bundle jettBundle = Platform.getBundle("org.eclips.equinox.http.jetty"); 
    Bundle httpRegistryBundle = Platform.getBundle("org.eclipse.equinox.http.registry"); 
    try { 
     jettBundle.stop(); 
     httpRegistryBundle.stop(); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 
} 

С эту конфигурацию я могу использовать

RequestDispatcher dispatcher = req.getRequestDispatcher("/webApp/start.jsp"); 
dispatcher.forward(req, resp); 

в моем сервлете без проблем.

Надеюсь, я смогу помочь другим с той же проблемой.

Смежные вопросы