Java’s Simple Web Server: Static HTTP servers facilitated

Uncategorized

Among the handiest new features included in the Java 18 release (March 2022) was the new Basic Web Server, that makes it simple to spin up and set up an HTTP file server. It likewise exposes an API that extends the existing httpserver plan for constructing basic use cases.

The new Simple Web Server is a beneficial tool that every Java developer need to have in their bag of tricks. Let’s examine it out!Java’s Simple

Web Server on the command line

Java’s brand-new jwebserver command makes it easy to run a fundamental web server. It is analogous to the popular SimpleHTTPServer tool in the Python world.The first step is to make certain you are running Java 18 or a later release. Type java– variation to learn what launch you are presently running. I suggest using SDKMan to manage JDK installs. It’s particularly beneficial for managing several versions.jwebserver fundamentals The most basic thing you can do with the Java Simple Web Server is to serve the present directory on

port 8000. Just enter the command displayed in Listing 1. Noting 1. No-arg web server$ jwebserver Binding to loopback by default. For all user interfaces utilize” -b 0.0.0.0 “or”-b::”. Serving/ home/matthewcarltyson and subdirectories on 127.0.0.1 port 8000 URL http://127.0.0.1:8000/ From there, if you go to your web browser and check out localhost:8000, you’ll see a listing of the file system, as shown in Figure 1. IDG Figure 1. A Basic Web Server circumstances operating on port 8000. Configuring the command line There are numerous common things you might need to do to fine-tune Basic Web Server on the command line. For example, you can alter the port, the address to bind to (the network user interface to

listen on), and the directory site to serve. In Listing 2, you can see how to listen on port 8080, on all interfaces, and in the / foo/bar directory site. Listing 2. Listen on port 8080, all user interfaces,/ foo/bar$jwebserver-b 0.0.0.0-p 8081 -d/ foo/bar You can get a list of

all the choices with $jwebserver -h. As you can see, the jwebserver command-line tool makes it possible to serve static files utilizing the simplest possible syntax. Next, we’ll take a look at the Easy Web Server API.Using Java’s Basic Web Server API The Easy Web Server Javadoc is an excellent starting point for finding out

about the API. The SimpleFileServer class exists in the com.sun.net.httpserver bundle.(This package likewise houses the older, lower-level APIs for building web servers.

The httpserver bundle extends that performance for simpler requirements.)The jwebserver CLI tool uses SimpleFileServer to do its work, and we can also use it programmatically.The SimpleFileServer class just deals with GET and HTTP/1.1. We can do some fascinating things with it, however. For example, this intro to dealing with Basic Web Server recommends a method to utilize the Google Java in-memory file system project to fake a file system for the handler.We’re going to utilize the idea of an in-memory file system to modify the FileHandler in SimpleFileServer to really serve a virtual file system from memory. Then, we’ll use the httpserver plan

to handle a POST to include a synthetic file to the synthetic file system. Serve a virtual file system from memory To start, let’s create a fast Maven project utilizing the following command:$mvn archetype: create-DgroupId=. com.infoworld- DartifactId= jsws-DarchetypeArtifactId=maven-archetype-quickstart Now, CD into the brand-new/ jsws directory. Set the compiler and source variations to 18 in the pom.xml, as described here. Next, add Google jimfs to the dependences, as displayed in Listing 3. Noting 3. The Google Java in-memory file system dependency com.google.jimfs jimfs 1.3.0 Now, we can modify the src/main/java/ App.java file to serve a phony file system. You can see the code to do

this in Noting 4. Noting 4. Serving the in-memory file system with SimpleFileServer package com.infoworld; import java.util.List;

import java.nio.charset.StandardCharsets; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.file.FileSystem

; import java.nio.file.Files; import java.nio.file.Path; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import com.sun.net.httpserver.SimpleFileServer; import static com.sun.net.httpserver.SimpleFileServer.OutputLevel; public class Mem personal< The concept in Noting 4 is to replicate the basic local file system API using Google's open source jimfs library, which implements the java.nio.file API however does everything in-memory, like a virtual file system. Using the library, you can specify your own directory courses and files programmatically. So, we develop our own virtual directory structure and hand that off to SimpleFileServer as the file handler.We set up the SimpleFileServer class programmatically: var server=SimpleFileServer.createFileServer(ADDR, root, OutputLevel.VERBOSE); This accepts the internet address to bind to, just like we saw from the command line. In this case, we pass in the undefined user interface and port 8080. After that comes the file system root. For this example, we'll provide it the Course things produced by our createDirectoryHierarchy()method.The createDirectoryHierarchy()technique utilizes jimfs to develop a Path things: FileSystem fs=Jimfs.newFileSystem( Configuration.unix());. It then occupies the Path with files and directories. The jimfs API for creating courses and files with material is not tough to grasp; for instance, we develop one with Course hi=foo.resolve("hello.txt ");. You can use most of the things like they were just typical Java NIO paths.Now, if we run this code and see localhost:8080, you'll see the directory listing and be able to search it and see file contents

, much like you would with a normal file server.Creating a virtual file Let’s take this idea one action further and add the capability to publish a brand-new file. We can use the com.sun.net.httpserver package to accept a POST request that will publish a new file to our in-memory file system. You can see this in Noting 5. Noting 5. Publishing a new file to the in-memory file system package com.infoworld; 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; import java.util.List; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import com.sun.net.httpserver.SimpleFileServer; import fixed com.sun.net.httpserver.SimpleFileServer.OutputLevel; public class App Handler to procedure POST requests and upload files fixed class UploadHandler executes HttpHandler personal final Path root; public UploadHandler (Path root)this.root =root; @Override public void deal with (HttpExchange exchange) throws IOException if(“POST “. equalsIgnoreCase(exchange.getRequestMethod())) else Approach Forbidden In Listing 5, we keep the majority of the class the very same, however at an HttpServer circumstances listening on port 8081. This is configured with our custom-made uploadHandler, which takes the uploaded information and utilizes it to compose a brand-new file to the root path that we produced in createDirectoryHierarchy.To test this out, we can run the entire server cluster with:$mvn tidy install officer: java-Dexec.mainClass=”com.infoworld.Mem”You can push a new file to the server with a CURL demand like the one in Listing 6. Noting 6. CURL POST a file $touch file.txt $curl -X POST-H”filename: file.txt”-d”@file. txt”http://localhost:8081/upload File published successfully: file.txt When you reload the localhost:8080/ file listings, you’ll see the brand-new file.txt and you can click it and view its contents.A quickly, basic, and versatile web server Simple Web Server is a welcome addition to the Java toolset. Not just does it make hosting files extremely easy with the CLI, it presents some fascinating possibilities with its API, especially when used in combination with the lower level HttpServer API.To discover more, have a look at these extra resources: Copyright © 2023 IDG Communications, Inc. Source

Leave a Reply

Your email address will not be published. Required fields are marked *