首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用com.sun.net.httpserver包含css文件?

如何使用com.sun.net.httpserver包含css文件?
EN

Stack Overflow用户
提问于 2016-03-22 02:26:58
回答 1查看 2.7K关注 0票数 2

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

代码语言:javascript
复制
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();
}
EN

回答 1

Stack Overflow用户

发布于 2016-06-13 15:29:51

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

对于像nginx这样的静态内容,要么使用轻量级的but服务器,要么使用轻量级的but服务器,但是发布应用程序将更加困难。

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

代码语言:javascript
复制
int port = 8080;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
// ... more server contexts
server.createContext("/static", new StaticFileServer());

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

代码语言:javascript
复制
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对。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36138885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档