Andro-Begg Andro-Begg - 7 months ago 170
Java Question

Serve static content with Jersey 2.22.2

I have a REST Api that I developed using Jersey, everything works fine when it comes to Json in / out. and that I'm consuming by Ajax.

However, due to Cross-Domain limitations on the browsers, I'd like to package the static website (JS / Images / HTMLs / CSS) on my WAR

This is how my web.xml looks like :

<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="RESTApi"
version="3.1">

<display-name>RESTApi</display-name>

<servlet>
<servlet-name>Test -> Jersey RESTful API</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.bc.api</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Test -> Jersey RESTful API</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>


and my static content on the project structure :

enter image description here

Now when I try to access
http://localhost:8080/static/index.html
it's processed as a REST call.

How can I make the static directory packages and accessed through the API?

Answer

You could use different url pattern for rest. For eample, for all rest api url pattern start with rest.http://localhost:8080/rest/ap/customer.

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="RESTApi" 
    version="3.1">

    <display-name>RESTApi</display-name>

    <servlet>
        <servlet-name>Test -> Jersey RESTful API</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.bc.api</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test -> Jersey RESTful API</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

For Static contents, you could static folder under WebContent directory, then you could access it :http://localhost:8080/static/index.html.

Comments