日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

微框架spark--api开发利器

發布時間:2025/4/5 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 微框架spark--api开发利器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

spark簡介

Spark(注意不要同Apache Spark混淆)的設計初衷是,可以簡單容易地創建REST API或Web應用程序。它是一個靈活、簡潔的框架,大小只有1MB。Spark允許用戶自己選擇設計應用程序的模板引擎以及選擇最適合他們項目的庫,比如,HTML解析功能就有Freemarker、Mustaches、Velocity、Jade、Handlebars、Pebble或Water等選項可供選擇,而且很少需要配置或樣板文件。不過,靈活簡單的代價是,用戶可選的功能減少??傊?#xff0c;Spark剔除了許多Java的臃腫之物,提供了一個最小化的、靈活的Web框架。但由于精簡程度較高,它缺少了一些功能,不適合用于大型Web應用程序的開發。

使用示例

1.在pom.xml文件上加入依賴:

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

2. 編寫代碼

import static spark.Spark.*;public class HelloWorld {public static void main(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"); });

路由匹配模式也可以包含通配符參數??梢愿鶕埱髮ο蟮耐ㄅ浞椒▉碓L問:

// 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.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.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

查詢參數Map

  查詢參數Map支持根據前綴將參數分組到map中。這可以對兩組參數進行分組,如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

  每個請求可以訪問在服務端創建的session,提供了下面的方法來訪問:

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

?

停止

  一個過濾器或者路由中快速停止一個請求的方法是:

        halt();

  你也可以在停止時,指定一個狀態。

        halt(401);
 或者:
  halt("This is the body");   或者
  halt(401, "Go away!"); 過濾器
  前置過濾器在請求處理前進行處理,可以讀取請求,讀取/修改響應。
  停止執行,使用halt方法:
before((request, response) -> {boolean authenticated;// ... check if authenticatedif (!authenticated) {halt(401, "You are not welcome here");} });

  后置過濾器在請求處理后進行,可以讀取請求,讀取/修改響應:

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

  過濾器也可以匹配請求(可選的),此時只有當路徑匹配時才進行處理:

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

直接跳轉

  你可以使用redirect幫助方法將瀏覽器頁面進行跳轉。

    response.redirect("/bar");

  你可以使用狀態碼3xx進行跳轉:

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

異常映射

  處理配置的所有的過濾器和路由的異常:

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

靜態文件

  使用staticFileLocation方法,你可以在classpath中指定一個文件夾為靜態文件提供服務。

注意,公共目錄不要包含在url中。一個文件/public/css/style.css訪問路徑為:http://{host}:{port}/css/style.css

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

  還可以使用externalStaticFileLocationMethod在設置一個外部目錄(不在classpath)為靜態文件提供服務:

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

響應轉換

  映射路由將處理方法轉換成外部輸出??梢酝ㄟ^擴展ResponseTransformer,傳遞它到映射方法來完成。下面是一個使用Gson將一個路由輸出轉換成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是一個有‘message’成員變量的bean):

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

你也可以使用java8的方法引用,因為ResponseTransformer是有一個方法的接口:

Gson gson = new Gson(); get("/hello", (request, response) -> new MyMessage("Hello World"), gson::toJson);

視圖和模板

TemplateViewRoute由一個路徑(url匹配的路徑)和一個實現了render方法的模板引擎組成。

不用調用toString()方法返回的結果作為模板的實體,TemplateViewRoute返回調用render方法作為結果。

這種類型route的主要目的是提供一個創建通用和可復用的使用模板引擎渲染輸出的組件。

Freemarker

使用Freemarkder模板引擎渲染對象到html。

maven依賴:

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

示例和源碼在?GitHub上。

Mustache

使用Mustache模板引擎渲染對象到html。

Maven依賴如下:

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

示例和源碼在GitHub上。

Velocity

使用velocity模板引擎渲染對象到html。

Maven依賴如下:

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

示例和源碼在GitHub上。

Handlebars

使用Handlebar模板引擎渲染對象到html。

Maven依賴如下:

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

示例和源碼在GitHub上

jada

使用jada模板引擎渲染對象到html。

Maven依賴如下:

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

示例和源碼在?GitHub上

Pebble

使用pebble模板引擎渲染對象到html。

Maven依賴如下:

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

示例和源碼在?GitHub上

Water

使用water模板引擎渲染對象到html。

Maven依賴如下:

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

示例和源碼在GitHub上

內嵌的web服務器

  獨立的Spark運行在一個嵌入的Jetty web服務器。

端口

默認情況下,Spark運行在4567端口。如果你想使用別的端口,使用port方法。在使用過濾器和路由時已經完成:

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

安全

你可以通過secure方法來設置connection為安全的。這必須在所有路由映射之前完成:

secure(keystoreFile, keystorePassword, truststoreFile, truststorePassword);

線程池

可以非常容易的設置最大的線程數:

int maxThreads = 8; threadPool(maxThreads);

還可以配置最新線程數和空閑過期時間:

int maxThreads = 8; int minThreads = 2; int timeOutMillis = 30000; threadPool(maxThreads, minThreads, timeOutMillis);

等待初始化

使用awaitInitialization() 方法來檢查服務器是否準備好,可以處理請求了。

這通常在一個獨立的線程中來做,例如在服務器啟動后運行一個健康監測模塊。

這個方法將使當前線程處于等待狀態直至Jetty服務器初始化完成。初始化等于的路由、過濾器。因此,若使用一個線程,請不要將該方法放到你定義的路由、過濾器之前。

awaitInitialization(); // Wait for server to be initialized

其它的web服務器

  為運行集群服務器(不是獨立服務器),需要實現spark.servlet.SparkApplication。必須在init方法中初始化路由,下面的過濾器也必須在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>

壓縮

若請求/響應報文頭中有此字段,壓縮將會自動完成。

生成Javadoc

從GitHub?上獲取到源碼后,運行下面的命令生成javadoc:

mvn javadoc:javadoc

生成結果放入到/target/site/apidocs目錄下。

示例和教程

示例可以從工程目錄中獲取GitHub

說明書可以從Spark tutorial page獲取。

參考文獻:

【1】http://sparkjava.com/documentation.html

【2】http://www.infoq.com/cn/news/2015/06/Java-Spark-Jodd-Ninja

?

?

?

?

?

?

  

?

轉載于:https://www.cnblogs.com/davidwang456/p/4655090.html

總結

以上是生活随笔為你收集整理的微框架spark--api开发利器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。