Knowing the SparkJava Framework

Keleno
Keleno
Published in
4 min readJun 17, 2021

I would like to share some of my knowledge in Spark Java in this article. I will carry my article in a way of answering the following questions What, Why, Where,When and How ? With some code examples. I will cover the rest of the things in upcoming articles.

Let’s see the questions that needs to be answered.

1.What is Spark Java?
2.What are the advantages of using SparkJava?
3.Why it is Used ?
4.How to Use It?
5.Example codes and Advantages

What is Spark Java?
Spark is a simple and lightweight Java web framework built for rapid development.Spark focuses on being as simple and straight-forward as possible, without the need for cumbersome (XML) configuration, to enable very fast web application development in pure Java with minimal effort. It’s a totally different paradigm when compared to the overuse of annotations for accomplishing pretty trivial stuff seen in other web frameworks, for example, JAX-RS implementations.

What are the advantages of using SparkJava?

It is an alternative to other Java web application frameworks such as JAX-RS,Play Framework and Spring MVC.

It runs on an embedded Jetty web server by default, but can be configured to run on other web servers.

It does not follow the Model — View — Control pattern used in other frameworks, such as Spring MVC.

Spark is intended for “quickly creating web-applications in Java with minimal effort.”.

Why it is used?

Java developer with neither the urge nor time to learn a new programming language, and we’re not planning to build a super large web application that scales in all directions, then Spark might be a great web framework to work with. It will have us up and running in minutes, and we don’t wan’t to think too much about configuration and boilerplate code (like you often have to in other Java web frameworks, like Spring or Vaadin).

How to Use It?

We can configure Spark java in a project by adding maven dependencies in our POM file like this

Add the maven dependency:

<dependency>     			<groupId>com.sparkjava</groupId>     			<artifactId>spark-core</artifactId>     			<version>2.1</version>  		</dependency>

Sample code to start with…

Example Code :

import static spark.Spark.*;public class HelloWorld {
public static void main(String[] args) {
get("/hello", (req, res) -> "Hello World");
}
}

To view the result ….
Try this on your browser :

http://localhost:4567/hello

* Spark Java by default uses the port 4567.

How to change the port?

If we want to set another port use setPort. This has to be done before using routes and filters:
setPort(9090);

Now the Spark will run on port 9090

Routes

The main building block of a Spark application is a set of routes. A route is made up of three simple pieces:
A verb(get, post, put, delete, head, trace, connect, options)
A path(/hello, /users/:name)
A callback(request, response) -> { }

Routes are matched in the order they are defined. The first route that matches the request is invoked
Route method’s example codes :

get("/", (request, response) -> {
// .. Show something ..
});
post("/", (request, response) -> {
// .. Create something ..
});
put("/", (request, response) -> {
// .. Update something ..
});
delete("/", (request, response) -> {
// .. annihilate something ..
});
options("/", (request, response) -> {
// .. appease something ..
});
Route method with Param example code :
get("/hello/:name", (request, response) -> {
return "Hello: " + request.params(":name");
});

Filters
We can add two different filters in Spark Java as Before and After filters.
Before filters are evaluated before each request and can read the request and read/modify the response.

The example code for before filter is

before((request, response) -> {
boolean authenticated;
// ... check if authenticated
if (!authenticated) {
halt(401, "You are not welcome here");
}
});

After filters are evaluated after each request and can read the request and read/modify the response:

The example code for after filter is

after((request, response) -> {
response.header("foo", "set by after filter");
});

Redirect :
We can trigger a browser redirect with the redirect helper method:
response.redirect(“/bar”);

We can also trigger a browser redirect with specific http 3XX status code:
response.redirect(“/bar”, 301); // moved permanently

Halting the server:

To immediately stop a request within a filter or route use:

halt();

We can also specify the status when halting:
halt(401);

Or the body:
halt(“This is the body”);

…or both:
halt(401, “Go away!”);
Stopping the Server:
By calling the stop() method the server is stopped and all routes are cleared.

Read similar articles from Keleno

Follow us on Linkedin

Visit Keleno | Facebook | Twitter

--

--

Keleno
Keleno
Editor for

We specialize in solving problems that matter by applying technology and innovation at scale. Stay tuned for updates !!