tgabb
tgabb

Reputation: 379

Why does HttpContext accept requests from all URI's beginning with specified path?

I have a java application that is running with the following java version

$ java -version
java version "11.0.3" 2019-04-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.3+12-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.3+12-LTS, mixed mode)

I was looking into using the built in HttpServer that is in java, and noticed that a HttpContext with path=/foo would accept requests to uri's beginning with said path, for example /foo123 /foobar /fooxxx.

public class IsThisABug {

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/context",IsThisABug::handleRequest);
        server.start();
        System.out.println("Server listening on " + server.getAddress());
    }


    private static void handleRequest(HttpExchange exchange) throws IOException {
        URI requestURI = exchange.getRequestURI();
        String response = "Hello From handleRequest: " + requestURI;
        System.out.println(response);
        exchange.sendResponseHeaders(200, response.getBytes().length);
        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}

If I go into postman and send a GET request to localhost:8080/context the following output is observed in the terminal window:

Hello From handleRequest: /context

And if I send a request to /contextBar the following output is seen

Hello From handleRequest: /contextBar

I have briefly looked into using import com.sun.net.httpserver.Filter as a means of rejecting any stray requests coming into my /context endpoint but I don't see why this should be necessary.

Does anyone know why this is happening?

Upvotes: 1

Views: 1205

Answers (0)

Related Questions