B
B
bit_rainbow2014-07-06 13:09:44
Java
bit_rainbow, 2014-07-06 13:09:44

Java standalone server with REST and static web - how to solve the problem?

There is one artifact in dependency:

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
     <version>2.10.1</version>
 </dependency>

The code:
public static void main(String[] args) {
        final URI baseUri = UriBuilder.fromUri("http://localhost").port(9998).build();

        //add test configs
        Set rest = new HashSet<Class>();
        rest.add(TestResource.class);
        final ResourceConfig config = new ResourceConfig(rest);

        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);

        try {
            //server.getServerConfiguration().addHttpHandler(new StaticHttpHandler("web/"),"/w");

            server.getServerConfiguration().addHttpHandler(new StaticHttpHandler("src/main/resources/web"),"/");

            server.start();
            System.out.println();
            System.out.println("Press enter to stop the server...");
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            server.shutdownNow();
        }
    }

In this case, the rest methods are not available, but the static page on "/" is torn off. Screen .
But when I change part of the code to:
server.getServerConfiguration().addHttpHandler(new StaticHttpHandler("src/main/resources/web"),"/www");

In this case, everything works, but the static page will be on / www, but not on /
Screen
How to make the static page be on / and api on / api?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iryndin, 2014-07-09
@iryndin

Mapping "/" means that all paths starting with "/" will be processed by your corresponding handler, that is, both "/" and "/api".
Accordingly, when the mapping is set to "/www", then the paths starting with "/www" are processed by the set handler. It no longer processes paths starting with "/api", and that is why your rest handler (by the way, the rest handler is not visible in the code you provided) works (i.e. serves requests along the "/ api" path).
All these web servers (tomcat, grizzly, jetty, etc.) look up the corresponding handler by url very simply: they go through the list of handlers and compare their mappings with the url that came in. First approached handlerand will process the request for this url. In order to put static on "/" and rest-api on "/api", you just need to map to "/api" at the very beginning of the list of handlers, and map to the most common path ("/") at the very end. Then everything will work correctly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question