【问题标题】:404 Not Found No context found for request404 Not Found 找不到请求的上下文
【发布时间】:2018-11-13 01:44:42
【问题描述】:

如下图所示,我的 HTML 索引页面位于静态文件夹中。如何将 localhost 指向 static/index.html

我自己在基本的 hello world 上尝试过。

static class MyHandler implements HttpHandler { 
    public void 
    handle(HttpExchange t) throws IOException { 
    String response = "Hello world"; 
        t.sendResponseHeaders(200, response.length()); 
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes()); os.close(); 
} 
}

我需要知道如何将默认 localhost:8080 指向我预先构建的现有 static/index.html 页面?

【问题讨论】:

    标签: java intellij-idea


    【解决方案1】:

    如果我在您的应用程序启动时正确理解了您的问题,您希望将您的页面显示为默认页面 请通过以下链接
    How to configure welcome file list in web.xml
    这会让你知道如何配置你的 web.xml 页面,让 tomcat 或任何其他 web 容器知道你的默认页面。

    你可以试试这个

    public class Test {
    
        public static void main(String[] args) throws Exception {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/welcomePage", new MyHandler());
            server.setExecutor(null); // creates a default executor
            server.start();
        }
    
        static class MyHandler implements HttpHandler {
            @Override
            public void handle(HttpExchange t) throws IOException {
                String response = "This is the response";
                // we do not set content type, headers, cookies etc.
            // resp.setContentType("text/html"); // while redirecting as
            // it would most likely result in an IllegalStateException
    
            // "/" is relative to the context root (your web-app name)
            RequestDispatcher view = req.getRequestDispatcher("/path/to/file.html");
            // don't add your web-app name to the path
    
            view.forward(req, resp);
            }
        }
    }
    

    【讨论】:

    • 没有tomcat。我正在运行 main()
    • 我在 github 上托管的项目中也没有看到任何 web.xml
    • 我猜你可能会为默认主页绑定一个默认上下文“/”。
    • 我已经更新了我的答案。请告诉我它是否适合你。否则我们可能会找到更好的方法。
    • 你是说你无法导入 RequestDispatcher 类?
    猜你喜欢
    • 2018-04-18
    • 2014-11-19
    • 2018-04-18
    • 2016-01-12
    • 2013-07-06
    • 2012-12-30
    • 2014-02-16
    • 2020-07-01
    • 2013-09-22
    相关资源
    最近更新 更多