Spark is a micro framework for creating web applications with the Java language. In this tutorial, I will show you all first step to work with Spark framework via a Hello World application.
OK, let’s get started.
First of all, I will create new Maven project as below:
To use Spark framework in our project, we need to add Spark dependency:
1 2 3 4 5 |
<dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.9.1</version> </dependency> |
Now, we can create a new Java class Application:
and using Spark framework to enable a request with URL “/helloworld” in our application. The content of class Application as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.huongdanjava.sparkhelloworld; import spark.Request; import spark.Response; import spark.Route; import spark.Spark; public class Application { public static void main(String[] args) { Spark.get("/helloworld", new Route() { @Override public Object handle(Request arg0, Response arg1) throws Exception { return "Hello World from Spark"; } }); } } |
In above code, I declared a GET method with URL “/helloworld” by using a static method get() in Spark. The second parameter of the static get() method is an object of the Route interface that allows us to define how we will process the request from the client. Here, when the client requests to our application with this URL, the response will be a text “Hello World from Spark”.
Because the Route interface is a Functional Interface, you can rewrite the code for the Application class using the Lambda Expression as follows:
1 2 3 4 5 6 7 8 9 10 11 |
package com.huongdanjava.sparkhelloworld; import static spark.Spark.get; public class Application { public static void main(String[] args) { get("/helloworld", (req, res) -> "Hello World from Spark"); } } |
Simply, don’t you? 😀
Now, we can run our application. Because this is a normal Java application with main() method, you just need right click on the Application class, choose Run As and then Java Application.
Spark will start a Jetty server on the port 4567 and deploy our application into it.
Result: