【问题标题】:How can I include css file using com.sun.net.httpserver?如何使用 com.sun.net.httpserver 包含 css 文件?
【发布时间】:2016-07-08 10:12:01
【问题描述】:

我正在尝试使用 com.sun.net.httpserver 类编写一个简单的 http 服务器。我在启动时将 html 文件 (index.html) 发送到浏览器,但我不知道如何包含外部 css 文件。当 css 代码放在 html 文件中时,它可以工作。我知道,该浏览器应该发送一个请求,向服务器询问 css 文件,但我不知道如何接收这个请求并将这个文件发送回浏览器。如果有帮助,我会在下面附上我的代码片段。

private void startServer()
{
    try
    {
        server = HttpServer.create(new InetSocketAddress(8000), 0);
    } 
    catch (IOException e) 
    {
        System.err.println("Exception in class : " + e.getMessage());
    }
    server.createContext("/", new indexHandler());
    server.setExecutor(null);
    server.start();
}

private static class indexHandler implements HttpHandler
{
    public void handle(HttpExchange httpExchange) throws IOException
    {   
        Headers header = httpExchange.getResponseHeaders();
        header.add("Content-Type", "text/html");
        sendIndexFile(httpExchange);            
    }
}

static private void sendIndexFile(HttpExchange httpExchange) throws IOException
{
    File indexFile = new File(getIndexFilePath());
    byte [] indexFileByteArray = new byte[(int)indexFile.length()];

    BufferedInputStream requestStream = new BufferedInputStream(new FileInputStream(indexFile));
    requestStream.read(indexFileByteArray, 0, indexFileByteArray.length);

    httpExchange.sendResponseHeaders(200, indexFile.length());
    OutputStream responseStream = httpExchange.getResponseBody();
    responseStream.write(indexFileByteArray, 0, indexFileByteArray.length);
    responseStream.close();
}

【问题讨论】:

  • 这行代码是做什么的server.createContext("/", new indexHandler());
  • 它创建一个与路径“/”关联的http上下文。该路径的所有请求都由 indexHandler 对象处理。
  • 如果你想写一个HTTP服务器,你需要了解一个HTTP请求和它的响应之间的关系。告诉你这相当于一个教程。
  • @bizkhit 对,你应该怎么做才能接受另一条路? (你的情况是css)
  • 创建新上下文?但我不知道这条路应该是什么样子。假设我在 C:\MyApp\src\com\xyz\view\style.css 中有我的 css 文件。我应该给出 createContext 方法的完整路径吗?

标签: java html css httpserver simplehttpserver


【解决方案1】:

没有用于处理静态内容的内置方法。你有两个选择。

要么使用轻量级网络服务器来处理像nginx 这样的静态内容,但比分发您的应用程序更困难。

或者创建您自己的文件服务类。为此,您必须在 Web 服务器中创建一个新的上下文:

int port = 8080;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
// ... more server contexts
server.createContext("/static", new StaticFileServer());

然后创建将为您的静态文件提供服务的类。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

@SuppressWarnings("restriction")
public class StaticFileServer implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String fileId = exchange.getRequestURI().getPath();
        File file = getFile(fileId);
        if (file == null) {
            String response = "Error 404 File not found.";
            exchange.sendResponseHeaders(404, response.length());
            OutputStream output = exchange.getResponseBody();
            output.write(response.getBytes());
            output.flush();
            output.close();
        } else {
            exchange.sendResponseHeaders(200, 0);
            OutputStream output = exchange.getResponseBody();
            FileInputStream fs = new FileInputStream(file);
            final byte[] buffer = new byte[0x10000];
            int count = 0;
            while ((count = fs.read(buffer)) >= 0) {
                output.write(buffer, 0, count);
            }
            output.flush();
            output.close();
            fs.close();
        }
    }

    private File getFile(String fileId) {
        // TODO retrieve the file associated with the id
        return null;
    }
}

对于方法getFile(String fileId);您可以实现任何方式来检索与 fileId 关联的文件。一个不错的选择是创建一个镜像 URL 层次结构的文件结构。如果您没有很多文件,则可以使用 HashMap 来存储有效的 id-file 对。

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 2014-08-26
    • 2022-11-19
    • 2015-05-11
    • 1970-01-01
    • 2016-04-26
    • 2011-12-24
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多