杰瑞科技汇

Java如何搭建HTTP服务器?

Of course! Building an HTTP server in Java can be done in several ways, ranging from using the built-in, simple server to using powerful, production-grade frameworks.

Java如何搭建HTTP服务器?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the most common approaches.

The Built-in Java HTTP Server (Simple & Quick)

This is the easiest way to create a basic HTTP server without any external libraries. It's perfect for learning, simple scripts, or internal tools. It was introduced in Java 6.

Key Characteristics:

  • Pros: No dependencies, simple to set up for basic needs.
  • Cons: Lacks advanced features (routing, middleware, templating, etc.), not suitable for high-performance production applications.

Example: A Simple "Hello, World!" Server

This code creates a server that listens on port 8080 and responds to all requests with "Hello, World!".

Java如何搭建HTTP服务器?-图2
(图片来源网络,侵删)
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class SimpleHttpServer {
    public static void main(String[] args) throws IOException {
        // 1. Create the HTTP server
        // The first argument is the port number.
        // The second argument is the backlog (queue length for incoming connections).
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        // 2. Create a context (a URL path) and associate it with a handler
        // The first argument is the path (e.g., "/hello").
        // The second argument is the handler for that path.
        server.createContext("/hello", new HelloHandler());
        // 3. Create a default handler for all other paths (optional but good practice)
        server.createContext("/", new DefaultHandler());
        // 4. Set the executor to handle requests (null means default)
        // The default executor creates a new thread for each request.
        // For a real application, you'd use a thread pool.
        server.setExecutor(null); // creates a default executor
        // 5. Start the server
        System.out.println("Server started on port 8080. Press Ctrl+C to stop.");
        server.start();
    }
    // Handler for the /hello path
    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // We are only handling GET requests
            if (!"GET".equals(exchange.getRequestMethod())) {
                exchange.sendResponseHeaders(405, -1); // 405 Method Not Allowed
                return;
            }
            // The response message
            String response = "Hello, World!";
            // Send the response headers
            // 200 OK is the standard success code
            exchange.sendResponseHeaders(200, response.length());
            // Get the output stream and write the response
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        }
    }
    // Default handler for all other paths
    static class DefaultHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "404 Not Found";
            exchange.sendResponseHeaders(404, response.length());
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        }
    }
}

How to Run:

  1. Save the code as SimpleHttpServer.java.
  2. Compile it: javac SimpleHttpServer.java
  3. Run it: java SimpleHttpServer
  4. Open your web browser or use curl to test it:
    • http://localhost:8080/hello
    • http://localhost:8080/ (will show 404)

Using a Third-Party Framework (Recommended for Most Applications)

For any real-world application, you should use a web framework. They provide essential features like routing, middleware, security, and much better performance.

Here are the most popular choices:

Framework Description Best For
Spring Boot The de-facto standard for enterprise Java. It's a massive ecosystem that simplifies building stand-alone, production-grade Spring-based applications. Microservices, large web applications, APIs.
SparkJava A lightweight, expressive framework inspired by Sinatra (Ruby) and Express.js (Node.js). It's incredibly easy to get started with. Small to medium-sized web apps, REST APIs, microservices.
Javalin A very lightweight and modern web framework for Java and Kotlin. It's designed to be simple, fast, and easy to learn. Beginners, microservices, REST APIs, Kotlin integration.
Vert.x A toolkit for building reactive applications on the JVM. It's not a full framework but a set of libraries for building high-performance, non-blocking applications. High-performance, low-latency, and scalable applications (e.g., real-time apps).

Example with SparkJava (Lightweight & Easy)

SparkJava is a great choice for its simplicity and minimal boilerplate.

Add the Dependency

If you're using a build tool like Maven, add this to your pom.xml:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.9.4</version> <!-- Check for the latest version -->
</dependency>

If you're using Gradle, add this to your build.gradle:

implementation 'com.sparkjava:spark-core:2.9.4' // Check for the latest version

Write the Code

This code does the same thing as the built-in server but is much more readable.

import static spark.Spark.*;
public class SparkJavaServer {
    public static void main(String[] args) {
        // Configure the port
        port(8080);
        // Define a route for GET requests to /hello
        get("/hello", (req, res) -> "Hello, World from Spark!");
        // Define a route with a path parameter
        get("/hello/:name", (req, res) -> {
            String name = req.params(":name");
            return "Hello, " + name + "!";
        });
        // A simple POST example
        post("/post", (req, res) -> {
            // You can access the request body
            String body = req.body();
            System.out.println("Received POST body: " + body);
            return "Received your POST request!";
        });
        System.out.println("SparkJava server started on port 8080.");
    }
}

How to Run:

  1. Make sure you have the dependency in your project.
  2. Run the main method.
  3. Test it:
    • http://localhost:8080/hello
    • http://localhost:8080/hello/Alice
    • Use curl to test the POST: curl -X POST -d "This is the data" http://localhost:8080/post

Example with Spring Boot (The Enterprise Standard)

Spring Boot is more complex to set up but provides a complete, production-ready environment out of the box.

Create a Project using Spring Initializr

The easiest way is to use the Spring Initializr.

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose a recent stable version (e.g., 3.x.x).
  • Project Metadata:
    • Group: com.example
    • Artifact: demo
    • Name: demo
    • Packaging: Jar
    • Java: 17 or higher
  • Dependencies: Click "ADD DEPENDENCIES" and add Spring Web.

Click "GENERATE", download the ZIP file, and extract it into your IDE.

Write the Code

Spring Boot uses annotations to define controllers and routes.

// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
// A REST Controller to handle web requests
@RestController
class HelloController {
    // Handles GET requests for /hello
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World from Spring Boot!";
    }
    // Handles GET requests with a path variable
    @GetMapping("/hello/{name}")
    public String sayHelloTo(@PathVariable String name) {
        return "Hello, " + name + "!";
    }
    // Handles POST requests
    @PostMapping("/greet")
    public String greet(@RequestBody String body) {
        System.out.println("Received POST body: " + body);
        return "Greetings received! You said: " + body;
    }
}

How to Run:

  1. Open the project in your IDE (IntelliJ, Eclipse, VS Code).
  2. Navigate to DemoApplication.java.
  3. Right-click and select "Run 'DemoApplication.main()'".
  4. The application will start on port 8080 by default.
  5. Test it just like the SparkJava example.

Summary: Which one should you choose?

Scenario Recommended Approach Why?
Learning / Simple Script Built-in HttpServer No dependencies, shows the fundamentals.
Quick API / Small Project SparkJava or Javalin Lightweight, easy to learn, minimal setup.
Enterprise / Large Project Spring Boot Full ecosystem, security, scalability, industry standard.
High-Performance / Real-time Vert.x Non-blocking architecture, excellent for high concurrency.
分享:
扫描分享到社交APP
上一篇
下一篇