Spark 2.0.0 支持 Java 8 Lambda
jopen 10年前
Spark是一个微型的Java Web框架,它的灵感来自于Sinatra,它的目的是让你以最小的代价创建出一个Java Web应用。最近更新到2.0.0,支持Java 8 ,支持Lambda,Demo代码看起来非常有吸引力
最新版本已经可以通过maven center仓库依赖进来
<dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.0.0</version> </dependency>
入门指南
import static spark.Spark.*; import spark.*; public class HelloWorld { public static void main(String[] args) { get("/hello", (request, response) -> { return "Hello World!"; }); } }
运行
http://localhost:4567/hello
是否非常简单?
基本功能
Spark的应用程序的主要构建块是一组路由。路由是由三个部分组成:
一个动词(get, post, put, delete, head, trace, connect, options)
路径(/hello, /users/:name)
一个回调(request, response) -> { }
路由匹配的顺序定义。调用第一个匹配的路由请求。
import static spark.Spark.*; import spark.Request; import spark.Response; import spark.Route; /** * A simple example just showing some basic functionality */ public class SimpleExample { public static void main(String[] args) { // setPort(5678); <- Uncomment this if you wan't spark to listen on a port different than 4567. get("/hello", (request, response) -> { return "Hello World!"; }); post("/hello", (request, response) -> { return "Hello World: " + request.body(); }); get("/private", (request, response) -> { response.status(401); return "Go Away!!!"; }); get("/users/:name", (request, response) -> { return "Selected user: " + request.params(":name"); }); get("/news/:section", (request, response) -> { response.type("text/xml"); return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><news>" + request.params("section") + "</news>"; }); get("/protected", (request, response) -> { halt(403, "I don't think so!!!"); return null; }); get("/redirect", (request, response) -> { response.redirect("/news/world"); return null; }); get("/", (request, response) -> { return "root"; }); } }