When we think about development using java frameworks, first things that come to our mind are huge frameworks with tedious configuration with a lot of redundant code. Spark reduces these problems very effectively, It is one of the main reasons behind its growth and popularity in the Java Web Development World.
INTRODUCTION
Recent trend has emerged as Java micro framework. Micro Frameworks provide very powerful and lightweight tools as comparison to massive features of JAVA EE and frameworks like Spring. So, Spark is great for micro framework.
Java Spark is a Micro framework that makes building HTTP-based(event RESTful ) APIs and simple web APPs kind of ridiculously easy. It is inspired by Ruby Sinatra. Spark’s intention is not to compete with Sinatra, or dozen of clones in different languages(Grafitty, Nancy, Flask, Sammy etc.). Its intention is to be used by Java Developers who want or need to develop in pure Java.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 totally different paradigm when compare to other over use of annotations for accomplishing pretty trivial stuff seen in JAX-RS)
Spark doesn’t force to configure XML, It has no annotations and requires very less configuration and follows Java 8 lambda syntax. Jetty is embedded web server, which is great.
Entities already using Spark
- playlyfe.com
- Apache
- Asana
- despegar.com
- Gosu and every day almost 10000 user using spark
FEATURES
- It Supports for all the cool HTTP verbs(and the other ones too)
get, post, put, head, trace, connect, options. - Request Access and Response configuration(Response Transformation). You can directly transform resopnse into Json form.
- Cookies
- Sessions
- Halting
- Filters
- Redirects
- Exception Mapping
RESPONSE RENDERING
Spark supports almost all latest template engine
- Freemarker
- Velocity
- Mustache
- Handlebars
- Jade
- Thymeleaf
- Jetbrick
- Pebble
- Water
VERSIONS
It’s first version(Spark 1.0) was released since 2011. Next Version Spark 2.0 released in 2014, the framework only supports Java 8 and it’s latest version is Spark 2.5.
GETTING STARTED
Getting Started in Spark is very Simple.It requires Java8 and Maven to run. First Step to add Spark Maven dependency in POM.XML:
<dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.5</version> </dependency>
The second step is create one simple concrete class:
public class Demo { public static void main(String[] args) { Spark.get("/", (request, response) -> "Spark has Ignited"); Spark.post("/hello", (request, response) -> "Welcome to Spark"); } }
and third step is compile this class, run the program: “java Demo” and goto browser and type:
http://localhost:4537/
or
http://localhost:4537/hello
If you want to test with command line:
curl http://localhost:4567/
HOW TO ACCESS STATIC RESOURCE
If you need to serve static file . It should be inside the public folder and Spark provides method to load static files:
public class SparkStaticFileDemo{ public static void main(String[] args) throws Exception{ //Public folder should be inside your classpath and all static file(HTML, CSS and JS) should be within public folder for staticFileLocation() staticFileLocation("/public"); //You can also assign an external folder (a folder not in the classpath) to serve static files by using the externalStaticFileLocation method. externalStaticFileLocation("src/resources/public"); get("/", (request, response) -> "Success"); } }
To Run Spark with Other Web Server and Serve Static files
To run Spark on other web server (instead of the embedded jetty server), an implementation of the interface spark.servlet.SparkApplication is needed. You have to initialize the routes in the init() method and the following filter has to be configured in your web.xml:
<web-app> <display-name>Agami</display-name> <filter> <filter-name>SparkFilter</filter-name> <filter-class>spark.servlet.SparkFilter</filter-class> <init-param> <param-name>applicationClass</param-name> <param-value>com.agami.MainServelet</param-value> </init-param> </filter> <filter-mapping> <filter-name>SparkFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping> </web-app>
And you need to create a class which implements SparkApplication interface:
public class MainServelet implements SparkApplication{ @Override public void init(){ Spark.staticFileLocation("/public"); Spark.get("/", (request, response) -> IOUtils.toString(Spark.class.getResourceAsStream("/public/index.html"))); } }
NOTE:
1.If You need some Authenication before Accessing Whole Application you can use before HTTP verb:
before((request, response) -> if (!request.ip().equals("127.0.0.1")) { response.redirect("/"); halt(401, "Authorization has failed"); } });
2. You can use use lambda expression to handle Exception:
exception(Exception.class, (ex, request, response)->{ response.status(500); response.body("Server Error"); });
3. Rendering Velocity Template
get("/welcome", (request, response) ->{ Map model = new HashMap(); return new ModelAndView(model, "welcome.vm"); }, new VelocityTemplateEngine());
Download Examples
Spark with tomcat and angularjs
Spark with Embedded Jetty and angularjs
References
http://sparkjava.com/
https://github.com/perwendel/spark