9 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Spark — Потрясающий веб-микрофреймворк для Java

Introduction to Spark Java

last modified July 6, 2020

This is an introductory tutorial of the Spark Java web framework. We introduce the Spark Java framework and provide three code examples.

Spark Java

Spark is a Java micro framework for creating web applications in Java 8 with minimal effort. Spark framework is a simple and lightweight Java web framework built for rapid development. It was inspired by Sinatra, a popular Ruby micro framework.

Spark uses Java 8’s lambda expressions extensively, which makes Spark applications a lot less verbose. In contrast to other Java web frameworks, Spark does not use heavily XML files or annotations.

Routes

A Spark application contains a set of routes. A route maps URL patterns to Java handlers.

A route has three parts:

  • a verb, including get, post, put, delete, head, trace, connect, and options
  • a path such as /first or /hello/:name
  • a callback (request, response) ->

First application

The first application returns a simple message. Gradle is used to build the application.

This is the project structure. The Gradle’s Java plugin expects the Java production code to be located in src/main/java directory.

This is the Gradle build file. It includes dependencies for Spark core components and the slf4j simple logger.

The applications returns the “First Spark application message” to the GET request. When we run the application, Spark starts an embedded Jetty web server.

The get() method maps the routes for HTTP GET requests. In the Spark lingo, a route is a handler A route is a URL pattern that is mapped to a handler. A handler can be a physical file or a

We build the application with gradle build command.

We run the application with gradle run command. An embedded Jetty server is started.

We send a GET request to the server with the curl tool. The built-in embedded Jetty server listens on port 4567 by default.

Hello application

The second application will respond with a greeting to the user. The client sends a name with the URL and the application responds with a greeting to the user.

This is the Gradle build file of the application.

This is the project structure.

The Spark application retrieves the request parameter, builds a message, and returns it to the caller.

The params() method returns the value of the provided route pattern parameter.

We build and run the application.

We send a request to the server; the URL includes a name. The application sends back a greeting.

Running Spark application in Tomcat

By default, Spark applications run in an embedded Jetty server. In this example, we show how to run a Spark Java application in Tomcat. This time we use Maven build tool and create a project in NetBeans.

Figure: NetBeans project structure

The figure shows how the project looks like in NetBeans.

This is the Maven build file.

This is the context.xml file.

In the web.xml deployment descriptor, we specify the spark.servlet.SparkFilter .

We implement the SparkApplication interface and specify the route in the init() method.

Finally, we run the Tomcat web server.

The NetBeans’ built-in Tomcat listens on port 8084.

Читать еще:  Как убрать повторяющиеся символы из строки в java

Template engines

Spark does not have its own templating system; it uses third-party engines. In the following two examples, we use Thymeleaf and FreeMarker.

Using Thymeleaf

In the following example, we are going to integrate the Thymeleaf template engine into our Spark application. Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

This is the directory structure of the project. The template files are located in the src/main/resources/templates directory.

Here we have the Gradle build file, which includes the spark-template-thymeleaf dependency.

The application reads the request parameter and puts it into the ModelAndView object.

An instance of the ThymeleafTemplateEngine is passed to the get() method.

This is the hello.html template file. It refers to the name variable which was passed with the ModelAndView object.

We get this output.

FreeMarker

In the following example, we are going to integrate the FreeMarker template engine into our Spark application. FreeMarker is a well established Java template engine.

This is the directory structure of the project. The template file is located in the src/main/resources/views directory.

Here we have the Gradle build file, which includes the spark-template-freemarker dependency.

We set up the same application for FreeMarker.

We configure FreeMarker with the Configuration class. The template files are going to be placed into the views directory, which must be located on the classpath.

The FreeMarkerEngine is passed to the get() method.

This is the hello.ftl template file; it refers to the name variable which was passed with the ModelAndView object.

This is the output.

In this tutorial, we have introduced the Spark Java framework.

Spark – A micro framework for creating web applications in Kotlin and Java 8 with minimal effort

Quick start

Kotlin

Run and view

Sponsors

Spark is sponsored by Feature Upvote. A big thanks to them for making further development of the project possible.

Built for productivity

Spark Framework is a simple and expressive Java/Kotlin web framework DSL built for rapid development. Sparks intention is to provide an alternative for Kotlin/Java developers that want to develop their web applications as expressive as possible and with minimal boilerplate. With a clear philosophy Spark is designed not only to make you more productive, but also to make your code better under the influence of Spark’s sleek, declarative and expressive syntax.

Lets you take full advantage of the JVM

The JVM offers one of the biggest programming ecosystems in the world. It has a lot of Java web frameworks, but pure Java web development has traditionally been very cumbersome. If you love the JVM, but hate verbose code and frameworks, Spark is the web framework for you. It will have you up and running in minutes, and you can even use it with Groovy or Kotlin or whatever you want. Spark is an expressive, lightweight and unopinionated pure Java (and Kotlin) web framework that doesn’t get in your way, unlike in other web frameworks, you can structure your application as you want.

Читать еще:  Как создавать ярлыки избранных сайтов на рабочем столе

Microservices, microservices everywhere!

2015 was the year of microservice hype, and now that you’re getting around to looking into it you’re about to realize that Spark is great for microservices. Microservices work best with micro frameworks, and Spark has your REST API ready to serve JSON in less than ten lines of code. Spark is mainly used for creating REST API’s, but it also supports a multitude of template engines. Why not create one Spark application for your backend and one for your frontend?

Some companies using Spark:

NodeJS developer? Using TypeScript? Try Spark instead!

Lately, a lot of server-side web development has been taken over by NodeJS, but a growing number of NodeJS developers are using TypeScript and other statically typed languages that compile to JavaScript. Why not go all the way and use a language that was actually designed with types, and intended to run on the server-side? You also get all the benefits of running your application on the JVM, where libraries aren’t deprecated every day. If you’re coming from ExpressJS, then Spark’s syntax will feel very familiar, and unlike a lot of JavaScript web frameworks, Spark won’t be deprecated tomorrow.

Typical usage

Our 2015 survey tells us that over 50% of Spark users use Spark to create REST APIs, while about 25% use Spark to create websites. About 15% of deployed Spark applications each serve more than 10.000 users a day. Click here to read the full survey.

Spark Framework is a free and open source Java Web Framework, released under the Apache 2 License | Contact | Team

The Spark micro framework

Join the DZone community and get the full member experience.

Jump into a code sample

Features (or lack thereof)

Spark’s API contains few features, but very focused ones.

Request and Response objects provide full control over HTTP headers and functionalities. You can access query and URL parameters; specific headers like Content-Length and Content-Type are provided by a dedicated method, while you can always access any header from the parametric interface. This interface is really equivalent to the Servlet API.

Routes can be provided in a sequential order, each specified for a particular HTTP method (GET or POST usually, but not exclusively) and linking to a callback which will be executed. The callback is the point of conjunction between your application and the HTTP world: separation of concerns is easy to maintain.

Filters are a series of hooks that can be inserted before or after the execution of a request; they can optionally match only certain routes. Filters, which are small objects where a single method should be implemented, are the most coupled mechanism introduced by the Spark framework.

How it works: containers

Spark is a bit different from the classic Java frameworks. It starts itself and configure the application with a main() method, not with the classic inversion of control mechanism where some servlets are deployed into a container.

The advantages of this approach are that it simplifies end-to-end testing, and gives you back the control over the lifecycle of your objects. An hexagonal application uses a few servlets just to wrap its own code, so why bother playing with servlets when you can have your own main?

Читать еще:  Какой стабилизатор изображения лучше оптический или цифровой?

The disadvantages of the approach are that you won’t get ant functionality from the container, which does not exist here; and you won’t be able to access the standard Servlet API but only Spark’s one (may be a sacrilege).

Actually Spark features Jetty as an embedded container, so the Servlet API is just wrapped by it. You can even run Spark applications in Tomcat or other web servers supporting servlets, and it will integrate like many other frameworks by providing a fixed web.xml. But in my opinion you can just go for Spring in that case.

How it works: configuration

Another pecularity of Spark is that configuration (like routes) are mapped via Java code: there are no XML files, no annotations, and no INIs.

Rather you can use a DSL written in Java, with quite a bit of easy to read static imports (and indeed used at the highest level of abstraction, not inserted in your domain objects.)

This syntax is inspired by Sinatra, a similar DSL for Ruby applications; in interpreted languages is quite common to use the language itself for configuration. After all, this choice forces you to treat configuration that may break the application as code; and when was the last time you changed a route specified in XML without changing any of the Java classes?

Is this a trend?

In general, in my little area of the programming world I’m noticing a softer approach to frameworks, where most of the functionality is provided via libraries instead of as invasive components inserted in the flow of control.

This is also where the PHP world is heading (I know Java developers won’t care, but still it’s interesting):

If you look around, every single framework seems to implement the MVC pattern. And most of them are advertised as MVC frameworks. but not Symfony2. Have a look at the documentation, and you will see that the MVC pattern is only mentioned once or twice, but Symfony2 is never defined as being an MVC framework. Why? [..] I don’t like MVC because that’s not how the web works. Symfony2 is an HTTP framework; it is a Request/Response framework. That’s the big deal. The fundamental principles of Symfony2 are centered around the HTTP specification. — Fabien Potencier

Conclusions

The Java platform is not necessarily tied to the mindset of giant enterprise frameworks; see also how beautifully the Play framework manages HTTP actions (although still with configuration over convention).

Moreover, it does not matter in which language you do develop web applications: at least you can embrace HTTP as the lowest common denominator instead of the MVC machine of a framework. You may not need it, and you may also start not to like it anymore.

голоса
Рейтинг статьи
Ссылка на основную публикацию
Статьи c упоминанием слов: