Spark 是一個基於Java的微Web框架

banq發表於2014-06-07
Spark是一個可像Node.js的Express那樣快速Web框架,它雖然和大資料處理框架Spark同名,但是它是基於Java的,受Ruby的Sinatra框架鼓舞,用於Java的Web快速開發,使用Java 8 Lambda編寫。

開啟一個帶URL的服務程式碼如下:

import static spark.Spark.*;

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

透過瀏覽器開啟http://localhost:4567/hello
就會看到Hello world

實現RESTful架構也非常簡單,如下:

import static spark.Spark.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import spark.Request;
import spark.Response;
import spark.Route;

/**
 * A simple CRUD example showing howto create, get, update and delete book resources.
 */
public class Books {

    /**
     * Map holding the books
     */
    private static Map<String, Book> books = new HashMap<String, Book>();

    public static void main(String[] args) {
        final Random random = new Random();

        // Creates a new book resource, will return the ID to the created resource
        // author and title are sent as query parameters e.g. /books?author=Foo&title=Bar
        post("/books", (request, response) -> {

                String author = request.queryParams("author");
                String title = request.queryParams("title");
                Book book = new Book(author, title);

                int id = random.nextInt(Integer.MAX_VALUE);
                books.put(String.valueOf(id), book);

                response.status(201); // 201 Created
                return id;
        });

        // Gets the book resource for the provided id
        get("/books/:id", (request, response) -> {
                Book book = books.get(request.params(":id"));
                if (book != null) {
                    return "Title: " + book.getTitle() + ", Author: " + book.getAuthor();
                } else {
                    response.status(404); // 404 Not found
                    return "Book not found";
                }
        });

        // Updates the book resource for the provided id with new information
        // author and title are sent as query parameters e.g. /books/<id>?author=Foo&title=Bar
        put("/books/:id", (request, response) -> {
                String id = request.params(":id");
                Book book = books.get(id);
                if (book != null) {
                    String newAuthor = request.queryParams("author");
                    String newTitle = request.queryParams("title");
                    if (newAuthor != null) {
                        book.setAuthor(newAuthor);
                    }
                    if (newTitle != null) {
                        book.setTitle(newTitle);
                    }
                    return "Book with id '" + id + "' updated";
                } else {
                    response.status(404); // 404 Not found
                    return "Book not found";
                }
        });

        // Deletes the book resource for the provided id 
        delete("/books/:id", (request, response) -> {
                String id = request.params(":id");
                Book book = books.remove(id);
                if (book != null) {
                    return "Book with id '" + id + "' deleted";
                } else {
                    response.status(404); // 404 Not found
                    return "Book not found";
                }
        });

        // Gets all available book resources (id's)
        get("/books", (request, response) -> {
                String ids = "";
                for (String id : books.keySet()) {
                   ids += id + " "; 
                }
                return ids;
        });

    }

}
<p class="indent">


更多程式碼使用案例見Github

該框架的Server底層目前可惜不是基於Netty或Vert.x等非同步IO的,可以在Jetty和Tomcat中執行,如果能直接整合Vet.x,就是一個完整的Java版的Node.js+Express.js了。

[該貼被banq於2014-06-07 09:18修改過]

相關文章