Spark Getting started





Getting started

Add the maven dependency:

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

Start coding:

import static spark.Spark.*;

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

Run and view:

http://localhost:4567/hello

That was easy, right? Spark is the simplest Java web framework to set up, while still providing enough functionality for many types of projects.

Stopping the Server

By calling the stop() method the server is stopped and all routes are cleared.

Routes

The main building block of a Spark application is a set of routes. A route is made up of three simple pieces:

  • verb (get, post, put, delete, head, trace, connect, options)
  • path (/hello, /users/:name)
  • callback (request, response) -> { }

Routes are matched in the order they are defined. The first route that matches the request is invoked.

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 patterns can include named parameters, accessible via the params method on the request object:

// matches "GET /hello/foo" and "GET /hello/bar"
// request.params(":name") is 'foo' or 'bar'
get("/hello/:name", (request, response) -> {
    return "Hello: " + request.params(":name");
});

Route patterns can also include splat (or wildcard) parameters. These parameters can be accessed by using the splat method on the request object:

// matches "GET /say/hello/to/world"
// request.splat()[0] is 'hello' and request.splat()[1] 'world'
get("/say/*/to/*", (request, response) -> {
    return "Number of splat parameters: " + request.splat().length;
});

Request

In the handle method request information and functionality is provided by the request parameter:

request.body();               // request body sent by the client
request.cookies();            // request cookies sent by the client
request.contentLength();      // length of request body
request.contentType();        // content type of request.body
request.headers();            // the HTTP header list
request.headers("BAR");       // value of BAR header
request.attributes();         // the attributes list
request.attribute("foo");     // value of foo attribute
request.attribute("A", "V");  // sets value of attribute A to V
request.host();               // "example.com"
request.ip();                 // client IP address
request.pathInfo();           // the path info
request.params("foo");        // value of foo path parameter
request.params();             // map with all parameters
request.port();               // the server port
request.queryMap();           // the query map
request.queryMap("foo");      // query map for a certain parameter
request.queryParams("FOO");   // value of FOO query param
request.queryParams();        // the query param list
request.raw();                // raw request handed in by Jetty
request.requestMethod();      // The HTTP method (GET, ..etc)
request.scheme();             // "http"
request.session();            // session management
request.splat();              // splat (*) parameters
request.url();                // "http://example.com/foo"
request.userAgent();          // user agent

Response

In the handle method response information and functionality is provided by the response parameter:

response.body("Hello");        // sets content to Hello
response.header("FOO", "bar"); // sets header FOO with value bar
response.raw();                // raw response handed in by Jetty
response.redirect("/example"); // browser redirect to /example
response.status(401);          // set status code to 401
response.type("text/xml");     // set content type to text/xml

Query Maps

Query maps allows you to group parameters to a map by their prefix. This allows you to group two parameters like user[name] and user[age] to a user map.

request.queryMap().get("user", "name").value();
request.queryMap().get("user").get("name").value();
request.queryMap("user").get("age").integerValue();
request.queryMap("user").toMap();

Cookies

request.cookies();                              // get map of all request cookies
request.cookie("foo");                          // access request cookie by name
response.cookie("foo", "bar");                  // set cookie with a value
response.cookie("foo", "bar", 3600);            // set cookie with a max-age
response.cookie("foo", "bar", 3600, true);      // secure cookie
response.removeCookie("foo");                   // remove cookie

Sessions

Every request has access to the session created on the server side, provided with the following methods:

request.session(true)                            // create and return session
request.session().attribute("user")              // Get session attribute 'user'
request.session().attribute("user", "foo")       // Set session attribute 'user'
request.session().removeAttribute("user", "foo") // Remove session attribute 'user'
request.session().attributes()                   // Get all session attributes
request.session().id()                           // Get session id
request.session().isNew()                        // Check is session is new
request.session().raw()                          // Return servlet object

Halting

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

halt();

You can also specify the status when halting:

halt(401);

Or the body:

halt("This is the body");

...or both:

halt(401, "Go away!");

Filters

Before filters are evaluated before each request and can read the request and read/modify the response. 
To stop execution, use halt:

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:

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

Filters optionally take a pattern, causing them to be evaluated only if the request path matches that pattern:

before("/protected/*", (request, response) -> {
    // ... check if authenticated
    halt(401, "Go Away!");
});

Redirects

You can trigger a browser redirect with the redirect helper method:

response.redirect("/bar");

You can also trigger a browser redirect with specific http 3XX status code:

response.redirect("/bar", 301); // moved permanently

Exception Mapping

To handle exceptions of a configured type for all routes and filters:

get("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});

Static Files

You can assign a folder in the classpath serving static files with the staticFileLocation method. Note that the public directory name is not included in the URL.
A file /public/css/style.css is made available as http://{host}:{port}/css/style.css

staticFileLocation("/public"); // Static files

You can also assign an external folder (not in the classpath) serving static files with the externalStaticFileLocation method.

externalStaticFileLocation("/var/www/public"); // Static files

ResponseTransformer

Mapped routes that transforms the output from the handle method. This is done by extending the ResponseTransformer and pass this to the mapping method. Example Of a route transforming output to JSON using Gson:

import com.google.gson.Gson;

public class JsonTransformer implements ResponseTransformer {

    private Gson gson = new Gson();

    @Override
    public String render(Object model) {
        return gson.toJson(model);
    }

}

and how it is used (MyMessage is a bean with one member 'message'):

get("/hello", "application/json", (request, response) -> {
    return new MyMessage("Hello World");
}, new JsonTransformer());

Views and Templates

A TemplateViewRoute is built up by a path (for url-matching) and the template engine holding the implementation of the 'render' method. Instead of returning the result of calling toString() as body the TemplateViewRoute returns the result of calling render method.

The primary purpose of this kind of Route is to provide a way to create generic and reusable components for rendering output using a Template Engine.

Freemarker

Renders objects to HTML using the Freemarker template engine.

Maven dependency:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-template-freemarker</artifactId>
    <version>2.0.0</version>
</dependency>

Velocity

Renders objects to HTML using the Velocity template engine.

Maven dependency:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-template-velocity</artifactId>
    <version>2.0.0</version>
</dependency>

Mustache

Renders objects to HTML using the Mustache template engine.

Maven dependency:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-template-mustache</artifactId>
    <version>1.0.0</version>
</dependency>

Port

By default, Spark runs on port 4567. If you want to set another port use setPort. This has to be done before using routes and filters:

setPort(9090); // Spark will run on port 9090

Embedded webserver

Standalone Spark runs on an embedded Jetty web server.

Other webserver

To run Spark on a web server instead of standalone first of all an implementation of the interface spark.servlet.SparkApplication is needed. In the init() method the routes should be initialized. In your web.xml the following filter needs to be configured:

<filter>
    <filter-name>SparkFilter</filter-name>
    <filter-class>spark.servlet.SparkFilter</filter-class>
    <init-param>
        <param-name>applicationClass</param-name>
        <param-value>com.company.YourApplication</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SparkFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Javadoc

After getting the source from GitHub run:

mvn javadoc:javadoc

The result is put in /target/site/apidocs

Examples

Examples can be found on the project's page on GitHub

Spark is created and maintained by  Per Wendel. Logo and website by  David Åse





优秀的个人博客,低调大师

微信关注我们

原文链接:https://yq.aliyun.com/articles/257794

转载内容版权归作者及来源网站所有!

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

相关文章

发表评论

资源下载

更多资源
优质分享Android(本站安卓app)

优质分享Android(本站安卓app)

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Oracle Database,又名Oracle RDBMS

Oracle Database,又名Oracle RDBMS

Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统。它是在数据库领域一直处于领先地位的产品。可以说Oracle数据库系统是目前世界上流行的关系数据库管理系统,系统可移植性好、使用方便、功能强,适用于各类大、中、小、微机环境。它是一种高效率、可靠性好的、适应高吞吐量的数据库方案。

Apache Tomcat7、8、9(Java Web服务器)

Apache Tomcat7、8、9(Java Web服务器)

Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。

Eclipse(集成开发环境)

Eclipse(集成开发环境)

Eclipse 是一个开放源代码的、基于Java的可扩展开发平台。就其本身而言,它只是一个框架和一组服务,用于通过插件组件构建开发环境。幸运的是,Eclipse 附带了一个标准的插件集,包括Java开发工具(Java Development Kit,JDK)。