微框架spark--api开发利器
spark簡(jiǎn)介
Spark(注意不要同Apache Spark混淆)的設(shè)計(jì)初衷是,可以簡(jiǎn)單容易地創(chuàng)建REST API或Web應(yīng)用程序。它是一個(gè)靈活、簡(jiǎn)潔的框架,大小只有1MB。Spark允許用戶自己選擇設(shè)計(jì)應(yīng)用程序的模板引擎以及選擇最適合他們項(xiàng)目的庫(kù),比如,HTML解析功能就有Freemarker、Mustaches、Velocity、Jade、Handlebars、Pebble或Water等選項(xiàng)可供選擇,而且很少需要配置或樣板文件。不過(guò),靈活簡(jiǎn)單的代價(jià)是,用戶可選的功能減少。總之,Spark剔除了許多Java的臃腫之物,提供了一個(gè)最小化的、靈活的Web框架。但由于精簡(jiǎn)程度較高,它缺少了一些功能,不適合用于大型Web應(yīng)用程序的開(kāi)發(fā)。
使用示例
1.在pom.xml文件上加入依賴:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-core</artifactId><version>2.2</version> </dependency>2. 編寫(xiě)代碼
import static spark.Spark.*;public class HelloWorld {public static void main(String[] args) {get("/hello", (req, res) -> "Hello World");}}3.允許代碼且查看結(jié)果
http://localhost:4567/hello是不是很簡(jiǎn)單?spark是最容易建立一個(gè)java web應(yīng)用的開(kāi)發(fā)框架,但它提供了對(duì)大多數(shù)類型的項(xiàng)目來(lái)說(shuō)足夠的功能。
停止服務(wù)器
通過(guò)調(diào)用stop()方法,服務(wù)將關(guān)閉且會(huì)清理掉所有的路由信息。
路由
一個(gè)spark應(yīng)用的主要模塊就是一組路由。路由有三部分組成:
? 一個(gè)方法。(get,post,put,delete,head,trace,connect,options).
一個(gè)路徑。(例如/hello, /users/:name)
一個(gè)回調(diào)。(request,response)->{}
? 路由的匹配是按照路由的定義順序匹配的。請(qǐng)求會(huì)觸發(fā)第一個(gè)匹配的路由。
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 .. });路由匹配模式可以包含命名參數(shù),根據(jù)請(qǐng)求對(duì)象的參數(shù)方法來(lái)訪問(wèn):
// 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"); });路由匹配模式也可以包含通配符參數(shù)??梢愿鶕?jù)請(qǐng)求對(duì)象的通配符方法來(lái)訪問(wèn):
// 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;});
請(qǐng)求
在處理方法中,請(qǐng)求參數(shù)提供了請(qǐng)求信息和功能:
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響應(yīng)
在處理方法中,響應(yīng)參數(shù)提供了響應(yīng)參數(shù)和功能:
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查詢參數(shù)Map
查詢參數(shù)Map支持根據(jù)前綴將參數(shù)分組到map中。這可以對(duì)兩組參數(shù)進(jìn)行分組,如user[name]和user[age]一樣。
request.queryMap().get("user", "name").value(); request.queryMap().get("user").get("name").value(); request.queryMap("user").get("age").integerValue(); request.queryMap("user").toMap()?
?
Cookie
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?
Session
每個(gè)請(qǐng)求可以訪問(wèn)在服務(wù)端創(chuàng)建的session,提供了下面的方法來(lái)訪問(wèn):
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 objec?
停止
一個(gè)過(guò)濾器或者路由中快速停止一個(gè)請(qǐng)求的方法是:
halt();你也可以在停止時(shí),指定一個(gè)狀態(tài)。
halt(401);或者:
halt("This is the body"); 或者
halt(401, "Go away!"); 過(guò)濾器
前置過(guò)濾器在請(qǐng)求處理前進(jìn)行處理,可以讀取請(qǐng)求,讀取/修改響應(yīng)。
停止執(zhí)行,使用halt方法:
before((request, response) -> {boolean authenticated;// ... check if authenticatedif (!authenticated) {halt(401, "You are not welcome here");} });
后置過(guò)濾器在請(qǐng)求處理后進(jìn)行,可以讀取請(qǐng)求,讀取/修改響應(yīng):
after((request, response) -> {response.header("foo", "set by after filter"); });過(guò)濾器也可以匹配請(qǐng)求(可選的),此時(shí)只有當(dāng)路徑匹配時(shí)才進(jìn)行處理:
before("/protected/*", (request, response) -> {// ... check if authenticatedhalt(401, "Go Away!"); });直接跳轉(zhuǎn)
你可以使用redirect幫助方法將瀏覽器頁(yè)面進(jìn)行跳轉(zhuǎn)。
response.redirect("/bar");
你可以使用狀態(tài)碼3xx進(jìn)行跳轉(zhuǎn):
response.redirect("/bar", 301); // moved permanentl
異常映射
處理配置的所有的過(guò)濾器和路由的異常:
get("/throwexception", (request, response) -> {throw new NotFoundException(); });exception(NotFoundException.class, (e, request, response) -> {response.status(404);response.body("Resource not found"); });靜態(tài)文件
使用staticFileLocation方法,你可以在classpath中指定一個(gè)文件夾為靜態(tài)文件提供服務(wù)。
注意,公共目錄不要包含在url中。一個(gè)文件/public/css/style.css訪問(wèn)路徑為:http://{host}:{port}/css/style.css
staticFileLocation("/public"); // Static files還可以使用externalStaticFileLocationMethod在設(shè)置一個(gè)外部目錄(不在classpath)為靜態(tài)文件提供服務(wù):
externalStaticFileLocation("/var/www/public"); // Static files響應(yīng)轉(zhuǎn)換
映射路由將處理方法轉(zhuǎn)換成外部輸出。可以通過(guò)擴(kuò)展ResponseTransformer,傳遞它到映射方法來(lái)完成。下面是一個(gè)使用Gson將一個(gè)路由輸出轉(zhuǎn)換成json的示例:
import com.google.gson.Gson;public class JsonTransformer implements ResponseTransformer {private Gson gson = new Gson();@Overridepublic String render(Object model) {return gson.toJson(model);}}使用上述類(MyMessage是一個(gè)有‘message’成員變量的bean):
get("/hello", "application/json", (request, response) -> {return new MyMessage("Hello World"); }, new JsonTransformer());你也可以使用java8的方法引用,因?yàn)镽esponseTransformer是有一個(gè)方法的接口:
Gson gson = new Gson(); get("/hello", (request, response) -> new MyMessage("Hello World"), gson::toJson);視圖和模板
TemplateViewRoute由一個(gè)路徑(url匹配的路徑)和一個(gè)實(shí)現(xiàn)了render方法的模板引擎組成。
不用調(diào)用toString()方法返回的結(jié)果作為模板的實(shí)體,TemplateViewRoute返回調(diào)用render方法作為結(jié)果。
這種類型route的主要目的是提供一個(gè)創(chuàng)建通用和可復(fù)用的使用模板引擎渲染輸出的組件。
Freemarker
使用Freemarkder模板引擎渲染對(duì)象到html。
maven依賴:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-freemarker</artifactId><version>2.0.0</version> </dependency>示例和源碼在?GitHub上。
Mustache
使用Mustache模板引擎渲染對(duì)象到html。
Maven依賴如下:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-mustache</artifactId><version>1.0.0</version> </dependency>示例和源碼在GitHub上。
Velocity
使用velocity模板引擎渲染對(duì)象到html。
Maven依賴如下:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-velocity</artifactId><version>2.0.0</version> </dependency>示例和源碼在GitHub上。
Handlebars
使用Handlebar模板引擎渲染對(duì)象到html。
Maven依賴如下:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-handlebars</artifactId><version>1.0.0</version> </dependency>示例和源碼在GitHub上
jada
使用jada模板引擎渲染對(duì)象到html。
Maven依賴如下:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-jade</artifactId><version>1.0.0</version> </dependency>示例和源碼在?GitHub上
Pebble
使用pebble模板引擎渲染對(duì)象到html。
Maven依賴如下:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-pebble</artifactId><version>1.0.0</version> </dependency>示例和源碼在?GitHub上
Water
使用water模板引擎渲染對(duì)象到html。
Maven依賴如下:
<dependency><groupId>com.sparkjava</groupId><artifactId>spark-template-water</artifactId><version>1.0.0</version> </dependency>示例和源碼在GitHub上
內(nèi)嵌的web服務(wù)器
獨(dú)立的Spark運(yùn)行在一個(gè)嵌入的Jetty web服務(wù)器。
端口
默認(rèn)情況下,Spark運(yùn)行在4567端口。如果你想使用別的端口,使用port方法。在使用過(guò)濾器和路由時(shí)已經(jīng)完成:
port(9090); // Spark will run on port 9090安全
你可以通過(guò)secure方法來(lái)設(shè)置connection為安全的。這必須在所有路由映射之前完成:
secure(keystoreFile, keystorePassword, truststoreFile, truststorePassword);線程池
可以非常容易的設(shè)置最大的線程數(shù):
int maxThreads = 8; threadPool(maxThreads);還可以配置最新線程數(shù)和空閑過(guò)期時(shí)間:
int maxThreads = 8; int minThreads = 2; int timeOutMillis = 30000; threadPool(maxThreads, minThreads, timeOutMillis);等待初始化
使用awaitInitialization() 方法來(lái)檢查服務(wù)器是否準(zhǔn)備好,可以處理請(qǐng)求了。
這通常在一個(gè)獨(dú)立的線程中來(lái)做,例如在服務(wù)器啟動(dòng)后運(yùn)行一個(gè)健康監(jiān)測(cè)模塊。
這個(gè)方法將使當(dāng)前線程處于等待狀態(tài)直至Jetty服務(wù)器初始化完成。初始化等于的路由、過(guò)濾器。因此,若使用一個(gè)線程,請(qǐng)不要將該方法放到你定義的路由、過(guò)濾器之前。
awaitInitialization(); // Wait for server to be initialized其它的web服務(wù)器
為運(yùn)行集群服務(wù)器(不是獨(dú)立服務(wù)器),需要實(shí)現(xiàn)spark.servlet.SparkApplication。必須在init方法中初始化路由,下面的過(guò)濾器也必須在web.xml中配置:
<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>壓縮
若請(qǐng)求/響應(yīng)報(bào)文頭中有此字段,壓縮將會(huì)自動(dòng)完成。
生成Javadoc
從GitHub?上獲取到源碼后,運(yùn)行下面的命令生成javadoc:
mvn javadoc:javadoc生成結(jié)果放入到/target/site/apidocs目錄下。
示例和教程
示例可以從工程目錄中獲取GitHub
說(shuō)明書(shū)可以從Spark tutorial page獲取。
參考文獻(xiàn):
【1】http://sparkjava.com/documentation.html
【2】http://www.infoq.com/cn/news/2015/06/Java-Spark-Jodd-Ninja
?
?
?
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/4655090.html
總結(jié)
以上是生活随笔為你收集整理的微框架spark--api开发利器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Exploring Micro-fram
- 下一篇: Catch Me If You ...