Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用com.sun.net.httpserver包含css文件?_Java_Html_Css_Httpserver_Simplehttpserver - Fatal编程技术网

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

Java 如何使用com.sun.net.httpserver包含css文件?,java,html,css,httpserver,simplehttpserver,Java,Html,Css,Httpserver,Simplehttpserver,我正在尝试使用com.sun.net.httpserver类编写一个简单的http服务器。我在启动时将html文件(index.html)发送到浏览器,但我不知道如何包含外部css文件。当css代码放在html文件中时,它就工作了。我知道,浏览器应该发送一个请求,向服务器请求css文件,但我不确定如何接收该请求并将该文件发送回浏览器。如果有帮助的话,我在下面附上我的代码片段 private void startServer() { try { server = H

我正在尝试使用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();
}

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

或者使用一个轻量级的Web服务器来处理静态内容,比如,但比分发应用程序要困难得多

或者创建自己的文件服务类。为此,您必须在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(字符串fileId);您可以实现检索与fileId关联的文件的任何方法。一个好的选择是创建一个镜像URL层次结构的文件结构。如果文件不多,可以使用HashMap存储有效的id文件对。

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