spark简介
Spark(注意不要同Apache Spark混淆)的设计初衷是,可以简单容易地创建REST API或Web应用程序。它是一个灵活、简洁的框架,大小只有1MB。Spark允许用户自己选择设计应用程序的模板引擎以及选择最适合他们项目的库,比如,HTML解析功能就有Freemarker、Mustaches、Velocity、Jade、Handlebars、Pebble或Water等选项可供选择,而且很少需要配置或样板文件。不过,灵活简单的代价是,用户可选的功能减少。总之,Spark剔除了许多Java的臃肿之物,提供了一个最小化的、灵活的Web框架。但由于精简程度较高,它缺少了一些功能,不适合用于大型Web应用程序的开发。
使用示例
1.在pom.xml文件上加入依赖:
com.sparkjava
spark-core
2.2
2. 编写代码
import static spark.Spark.*;public classHelloWorld {public static voidmain(String[] args) {
get("/hello", (req, res) -> "Hello World");
}
}
3.允许代码且查看结果
http://localhost:4567/hello
是不是很简单?spark是最容易建立一个java web应用的开发框架,但它提供了对大多数类型的项目来说足够的功能。
停止服务器
通过调用stop()方法,服务将关闭且会清理掉所有的路由信息。
路由
一个spark应用的主要模块就是一组路由。路由有三部分组成:
一个方法。(get,post,put,delete,head,trace,connect,options).
一个路径。(例如/hello, /users/:name)
一个回调。(request,response)->{}
路由的匹配是按照路由的定义顺序匹配的。请求会触发第一个匹配的路由。
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 ..
});
路由匹配模式可以包含命名参数,根据请求对象的参数方法来访问:
//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");
});
路由匹配模式也可以包含通配符参数。可以根据请求对象的通配符方法来访问:
//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;</