Java18简单Web服务器案例

wen java案例 2

本文目录导读:

Java18简单Web服务器案例

  1. 最简单的Web服务器(使用命令行工具)
  2. 使用SimpleFileServer API(编程方式)
  3. 自定义HTTP处理器(更灵活的方案)
  4. 项目结构示例
  5. Maven配置(如果需要)
  6. 运行示例
  7. 测试服务器

我来为您提供一个Java 18的简单Web服务器案例,Java 18引入了SimpleWebServer,这是一个命令行工具,也提供了编程API。

最简单的Web服务器(使用命令行工具)

Java 18自带了一个简单的Web服务器工具,可以直接在命令行使用:

# 在指定目录启动Web服务器,默认端口8000
jwebserver -d /path/to/your/directory -p 8000
# 或者使用简写
jwebserver --directory /path/to/your/directory --port 8000

使用SimpleFileServer API(编程方式)

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import java.net.InetSocketAddress;
import java.nio.file.Path;
public class SimpleStaticServer {
    public static void main(String[] args) throws Exception {
        // 指定静态文件目录
        Path root = Path.of("/path/to/your/web/files");
        // 创建简单的文件服务器
        HttpServer server = SimpleFileServer.createFileServer(
            new InetSocketAddress(8080),
            root,
            SimpleFileServer.OutputLevel.VERBOSE
        );
        // 启动服务器
        server.start();
        System.out.println("静态文件服务器已启动: http://localhost:8080");
        System.out.println("服务目录: " + root.toAbsolutePath());
        System.out.println("按 Ctrl+C 停止服务器");
    }
}

自定义HTTP处理器(更灵活的方案)

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
public class SimpleWebServer {
    private HttpServer server;
    private Map<String, HttpHandler> routes = new HashMap<>();
    public static void main(String[] args) throws IOException {
        SimpleWebServer webServer = new SimpleWebServer();
        webServer.start(8080);
    }
    public void start(int port) throws IOException {
        // 创建HTTP服务器
        server = HttpServer.create(new InetSocketAddress(port), 0);
        // 注册不同的路由
        registerRoutes();
        // 添加默认处理器(处理404)
        server.createContext("/", exchange -> {
            if (!routes.containsKey(exchange.getRequestURI().getPath())) {
                handle404(exchange);
            }
        });
        // 启动服务器
        server.setExecutor(null); // 使用默认的执行器
        server.start();
        System.out.println("Web服务器已启动: http://localhost:" + port);
        System.out.println("可用路由:");
        routes.keySet().forEach(route -> System.out.println("  " + route));
    }
    private void registerRoutes() {
        // 首页路由
        routes.put("/", exchange -> {
            String response = """
                <!DOCTYPE html>
                <html>
                <head>
                    <title>我的第一个Java Web服务器</title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 20px; }
                        h1 { color: #4CAF50; }
                        .info { background-color: #f0f0f0; padding: 15px; 
                                border-radius: 5px; margin-top: 20px; }
                        a { color: #2196F3; text-decoration: none; }
                        a:hover { text-decoration: underline; }
                    </style>
                </head>
                <body>
                    <h1>🚀 我的简单Web服务器</h1>
                    <p>这是一个使用 Java 18 创建的简单Web服务器</p>
                    <div class="info">
                        <h3>可用的路由:</h3>
                        <ul>
                            <li><a href="/">/</a> - 首页</li>
                            <li><a href="/about">/about</a> - 关于页面</li>
                            <li><a href="/api/time">/api/time</a> - 获取当前时间</li>
                            <li><a href="/api/user">/api/user</a> - 用户信息JSON</li>
                            <li><a href="/json">/json</a> - 返回JSON数据</li>
                            <li><a href="/form">/form</a> - 提交表单</li>
                        </ul>
                        <p>当前时间: %s</p>
                    </div>
                </body>
                </html>
                """.formatted(LocalDateTime.now());
            sendResponse(exchange, 200, "text/html", response);
        });
        // 关于页面
        routes.put("/about", exchange -> {
            String response = """
                <!DOCTYPE html>
                <html>
                <head>
                    <title>lt;/title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 20px; }
                        h1 { color: #2196F3; }
                        .highlight { background-color: #FFEB3B; padding: 2px 5px; }
                    </style>
                </head>
                <body>
                    <h1>关于这个服务器</h1>
                    <p>这个服务器使用以下技术构建:</p>
                    <ul>
                        <li><strong>Java版本:</strong> 18</li>  
                        <li><strong>HTTP API:</strong> com.sun.net.httpserver</li>
                        <li><strong>特性:</strong> 简单、快速、轻量级</li>
                    </ul>
                    <p>返回 <a href="/">首页</a></p>
                </body>
                </html>
                """;
            sendResponse(exchange, 200, "text/html", response);
        });
        // 时间API
        routes.put("/api/time", exchange -> {
            Map<String, String> timeData = new HashMap<>();
            timeData.put("time", LocalDateTime.now().toString());
            timeData.put("epoch", String.valueOf(System.currentTimeMillis()));
            String json = toJson(timeData);
            sendResponse(exchange, 200, "application/json", json);
        });
        // 用户信息JSON
        routes.put("/api/user", exchange -> {
            Map<String, Object> user = new HashMap<>();
            user.put("id", 1);
            user.put("name", "张三");
            user.put("email", "zhangsan@example.com");
            user.put("roles", new String[]{"admin", "user"});
            String json = toJson(user);
            sendResponse(exchange, 200, "application/json", json);
        });
        // 返回JSON示例
        routes.put("/json", exchange -> {
            Map<String, Object> data = Map.of(
                "message", "欢迎使用JSON API",
                "status", "success",
                "code", 200
            );
            String json = toJson(data);
            sendResponse(exchange, 200, "application/json", json);
        });
        // 表单处理
        routes.put("/form", exchange -> {
            if ("GET".equals(exchange.getRequestMethod())) {
                // 显示表单
                String response = """
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>表单提交</title>
                        <style>
                            body { font-family: Arial, sans-serif; padding: 20px; }
                            form { max-width: 400px; margin: 20px 0; }
                            input[type="text"], textarea { 
                                width: 100%; padding: 8px; margin-bottom: 10px; 
                            }
                            input[type="submit"] {
                                background-color: #4CAF50; color: white; 
                                padding: 10px 20px; border: none; cursor: pointer;
                            }
                        </style>
                    </head>
                    <body>
                        <h1>表单提交</h1>
                        <form method="POST" action="/form">
                            <label>姓名:</label><br>
                            <input type="text" name="name"><br><br>
                            <label>留言:</label><br>
                            <textarea name="message" rows="4"></textarea><br><br>
                            <input type="submit" value="提交">
                        </form>
                        <p>返回 <a href="/">首页</a></p>
                    </body>
                    </html>
                    """;
                sendResponse(exchange, 200, "text/html", response);
            } else if ("POST".equals(exchange.getRequestMethod())) {
                // 处理表单提交
                String requestBody = new String(exchange.getRequestBody().readAllBytes());
                sendResponse(exchange, 200, "text/plain", 
                    "表单接收成功!\n数据: " + requestBody);
            }
        });
    }
    private void sendResponse(HttpExchange exchange, int statusCode, 
                              String contentType, String response) throws IOException {
        byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set("Content-Type", contentType);
        exchange.getResponseHeaders().set("Connection", "close");
        exchange.sendResponseHeaders(statusCode, bytes.length);
        OutputStream os = exchange.getResponseBody();
        os.write(bytes);
        os.close();
    }
    private void handle404(HttpExchange exchange) throws IOException {
        String response = """
            <!DOCTYPE html>
            <html>
            <head><title>404 - Not Found</title></head>
            <body>
                <h1>404 - 页面不存在</h1>
                <p>抱歉,请求的资源不存在。</p>
                <p><a href="/">返回首页</a></p>
            </body>
            </html>
            """;
        sendResponse(exchange, 404, "text/html", response);
    }
    private String toJson(Map<?, ?> map) {
        StringBuilder json = new StringBuilder("{");
        int index = 0;
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (index++ > 0) {
                json.append(",");
            }
            json.append("\"")
                .append(escapeJson(String.valueOf(entry.getKey())))
                .append("\":\"")
                .append(escapeJson(String.valueOf(entry.getValue())))
                .append("\"");
        }
        json.append("}");
        return json.toString();
    }
    private String escapeJson(String text) {
        return text.replace("\\", "\\\\")
                   .replace("\"", "\\\"")
                   .replace("\n", "\\n")
                   .replace("\r", "\\r");
    }
    // 停止服务器的方法
    public void stop() {
        if (server != null) {
            server.stop(0);
            System.out.println("服务器已停止");
        }
    }
}

项目结构示例

web-server/
├── src/
│   └── com/example/server/
│       └── SimpleWebServer.java
├── web/
│   ├── index.html
│   ├── css/
│   │   └── style.css
│   └── images/
├── pom.xml (如果需要Maven)
└── README.md

Maven配置(如果需要)

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>simple-web-server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>18</source>
                    <target>18</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

运行示例

# 编译
javac -d out SimpleWebServer.java
# 运行
java -cp out SimpleWebServer
# 或者使用Java 18的新运行时方式
java --source 18 SimpleWebServer.java

测试服务器

启动后,访问以下URL:

  • http://localhost:8080/ - 首页
  • http://localhost:8080/about - 关于页面
  • http://localhost:8080/api/time - 获取时间JSON
  • http://localhost:8080/api/user - 用户信息JSON
  • http://localhost:8080/form - 表单页面

这个Web服务器虽然简单,但提供了基本的HTTP功能,适合学习、开发和测试使用,可以根据需要扩展更多功能,比如添加路由参数、数据库连接、模板引擎等。

抱歉,评论功能暂时关闭!