繁体   English   中英

仅使用Jersey和Java创建简单的html服务器

[英]Creating a simple html server with Jersey and Java only

不知道为什么我很难找到一种使用Jersey制作简单Web服务器的方法。

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;
    }
}

@Path("api")
public class RestAPI {


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

而且我可以做http:// localhost:4444 / api并获得“ this works”。 现在,如何允许基于传入URL的html文件? 我获得了各种MediaType / mimi信息,但是我无法在线找到任何内容来告诉我如何仅基于传入URL返回文件。

假设您需要返回的文件打包在您的WAR文件中,则可以尝试以下解决方案:

使用谷歌番石榴

@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();
    }
}

使用纯Java代码

@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"));
        }
    }
}

例如, fileName可以是assets/index.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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