Hello World with Spark framework

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:

Hello World with Spark framework

To use Spark framework in our project, we need to add Spark dependency:

Now, we can create a new Java class Application:

Hello World with Spark framework

and using Spark framework to enable a request with URL “/helloworld” in our application. The content of class Application as below:

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:

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:

Hello World with Spark framework

 

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment