簡體   English   中英

如何使用Jetty為Angular應用程序提供服務,還可以使用與Jersey相同的服務器?

[英]How can I serve an Angular app using Jetty and also use the same server along with Jersey?

我正在開發一個應用程序,其前端將使用Angular開發,后端使用Java / Jersey。 我使用Jetty作為http服務器。 我的目錄結構如下:

src
    main
        java
            com.scibor
                Main
                SandboxResource
        webapp
            WEB-INF
                web.xml
            index.html
            bower_components . . .
            app.js

Main ,我啟動了我的Jetty Server,如下所示:

Server server = new Server(PORT);

WebAppContext context = new WebAppContext();

context.setResourceBase("src/main/webapp");

context.setContextPath("/");
context.setServer(server);

server.setHandler(context);

try {
    server.start();
    server.join();
} catch (Exception e) {
    e.printStackTrace();
}

我的web.xml配置如下:

<display-name>Web App</display-name>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

<servlet>
    <servlet-name>jersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

    <!-- Adds JSON processing to map java classes to JSON text in both directions -->
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

    <!-- Tell the Jersey framework where to search for services.  Also, JAX-RS is needed for the JSON serialization -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.scibor</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>jersey</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<mime-mapping>
    <extension>json</extension>
    <mime-type>text/html</mime-type>
</mime-mapping>

我的問題是,在這種配置下,只有MyResource中指定的RESTful端點被選中。 但是,如果我去localhost:8080/它告訴我沒有找到資源。 如果我將資源庫更改為:

context.setResourceBase("src/main/webapp/index.html");

當我訪問localhost:8080時,它現在提供了我的角度項目localhost:8080但它現在沒有正確地提供任何我的RESTful端點。 我如何配置這個以便在訪問localhost:8080時提供角度應用程序,但是RESTful端點是否可以訪問?

你有一些選擇。 一個簡單的方法是將帶有index.html的角度基目錄插入到后端應用程序的文件夾中。 所以Angular app的url將是'localhost:8080 / app',你的端點將在'localhost:8080'上提供。 這將解決跨源政策問題。 第二種解決方案是使用grunt-proxy,它會將您的端點重定向到不同的端口。 如何使用grunt代理

答案實際上包含在<url-pattern>/*</url-pattern>行中。 它似乎指定了Jersey的基本URL,但/*是索引的基本URL,因此沒有任何服務。 將其更改為/server修復了問題,並允許我不僅提供角度應用程序,還可以命中Jersey端點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM