SimpleServer

Origin

Oracle JDK provides a simple Http server class called HttpServer, which is a sun-proprietary package located under com.sun.net.httpserver. It must be introduced with rt.jar to be used. Hutool encapsulates this with SimpleServer to implement simple Http request processing without introducing containers such as Tomcat or Jetty.

SimpleServer was introduced after Hutool-5.3.0, please upgrade to the latest version

Usage

  1. Starting an Http service is very simple:
HttpUtil.createServer(8888).start();

You can access it through your browser at http://localhost:8888/, but any path accessed at this time will result in a 404.

  1. Handling simple requests:
HttpUtil.createServer(8888)
    .addAction("/", (req, res)->{
        res.write("Hello Hutool Server");
    })
    .start();

Here we define a simple action bound to the “/” path. At this time, we can visit it and output “Hello Hutool Server”.

Similarly, by calling the addAction method, we can define the processing rules for different paths to achieve the corresponding functionality.

Simple File Server

Hutool provides a simple file service by default, which means defining a root directory allows you to directly access the resources under the directory through the request path. The default request is for index.html, similar to Nginx.

HttpUtil.createServer(8888)
    // Set the default root directory
    .setRoot("D:\\workspace\\site\\hutool-site")
    .start();

At this time, visiting http://localhost:8888/ will allow you to access the HTML static pages.

hutool-site is the source code project for the Hutool homepage, which can be found at: https://gitee.com/loolly_admin/hutool-site. Download it and use SimpleServer to achieve offline documentation.

Reading Request and Return Content

Sometimes we need to customize the reading of request parameters, and then access different data based on the parameters and organize the return. At this time, we can customize the Action to complete it:

  1. Returning JSON data:
HttpUtil.createServer(8888)
    // Test returning JSON data
    .addAction("/restTest", (request, response) ->
    		response.write("{\"id\": 1, \"msg\": \"OK\"}", ContentType.JSON.toString())
    ).start();
  1. Obtaining form data and returning it:
HttpUtil.createServer(8888)
    // http://localhost:8888/formTest?a=1&a=2&b=3
    .addAction("/formTest", (request, response) ->
        response.write(request.getParams().toString(), ContentType.TEXT_PLAIN.toString())
    ).start();

File Upload

In addition to regular Http services, Hutool also encapsulates file upload operations:

HttpUtil.createServer(8888)
    .addAction("/file", (request, response) -> {
        final UploadFile file = request.getMultipart().getFile("file");
        // Pass in the directory, and create a file with the filename in the HTTP header by default
        file.write("d:/test/");
        response.write("OK!", ContentType.TEXT_PLAIN.toString());
    })
    .start();