简体   繁体   中英

Creating a simple html server with Jersey and Java only

Not sure why I'm having so much trouble finding a way to make a simple webserver with Jersey.

public class AnotherJerseyHttpServer {

    public static void main(String[] args) throws IOException {
        System.out.println("Starting Crunchify's Embedded Jersey HTTPServer...\n");
        HttpServer webServer = createHttpServer();
        webServer.start();
        System.out.println(String.format("\nJersey Application Server started with WADL available at " + "%sapplication.wadl\n", getURI()));
        System.out.println("Started Crunchify's Embedded Jersey HTTPServer Successfully !!!");
    }

    public static HttpServer createHttpServer() throws IOException {
        ResourceConfig rc = new PackagesResourceConfig("com.daford");
        // This tutorial required and then enable below line: http://crunfy.me/1DZIui5
        //rc.getContainerResponseFilters().add(CrunchifyCORSFilter.class);
        return HttpServerFactory.create(getURI(), rc);
    }

    private static URI getURI() {
        return UriBuilder.fromUri("http://" + sHostname() + "/").port(4444).build();
    }

    private static String sHostname() {
        String hostName = "localhost";
        try {
            hostName = InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostName;
    }
}

AND

@Path("api")
public class RestAPI {


    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String get() {
        return "this works";
    }
}

And I can do http://localhost:4444/api and get "this works". Now how do I allow for an html file based on the incoming URL? I get the various MediaType/mimi info, but I can't find anything online to tell me how to just return a file based on the incoming URL.

Assuming that the file you need to return is packed in your WAR file, you could try the following solutions:

Using Google Guava

@Path("/{fileName: .+}")
@Produces(MediaType.TEXT_HTML)
public class HtmlResource {

    @GET
    public Response getPage(@PathParam("fileName") String fileName) throws IOException {
        URL url = Resources.getResource(fileName);
        return Response.ok(Resources.toString(url, Charsets.UTF_8)).build();
    }
}

Using Plain Java Code

@Path("/{fileName: .+}")
@Produces(MediaType.TEXT_HTML)
public class HtmlResource {

    @GET
    public Response getPage(@PathParam("fileName") String fileName) throws IOException {
        InputStream stream = HtmlResource.class.getClassLoader()
                                 .getResourceAsStream(fileName);
        String responseContent = read(stream);
        return Response.ok(responseContent).build();
    }

    private String read(InputStream stream) throws IOException {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(
                                             stream, StandardCharsets.UTF_8))) {
            return buffer.lines().collect(Collectors.joining("\n"));
        }
    }
}

For example, the fileName can be assets/index.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM