Skip to content

Instantly share code, notes, and snippets.

@izquiratops
Created February 21, 2020 08:31
Show Gist options
  • Save izquiratops/1f77f7ca171fda24f38c798b9c018838 to your computer and use it in GitHub Desktop.
Save izquiratops/1f77f7ca171fda24f38c798b9c018838 to your computer and use it in GitHub Desktop.
Spark WebServer Template
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>testing-webserver</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
import static spark.Spark.*;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
public class WebServer {
public static void main(String[] args) {
enableCORS("*", "GET", "Content-disposition");
// Hello World http://localhost:4567/hello
get("/hello", (req, res) -> "Hello World");
// Download a File Example
get("/file", ((request, response) -> {
response.header("Content-disposition", "attachment; filename=seal.jpg;");
File file = new File("C:\\Users\\jicas\\Pictures\\seal.jpg");
// OutputStream 101: https://www.baeldung.com/java-outputstream
OutputStream outputStream = response.raw().getOutputStream();
outputStream.write(Files.readAllBytes(file.toPath()));
outputStream.flush();
return response;
}));
}
private static void enableCORS(final String origin, final String methods, final String headers) {
options("/*", (request, response) -> {
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
before((request, response) -> {
response.header("Access-Control-Allow-Origin", origin);
response.header("Access-Control-Request-Method", methods);
response.header("Access-Control-Allow-Headers", headers);
response.header("Access-Control-Expose-Headers", headers);
// Allow by type (if needed)
// response.type("application/json");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment