Javalin框架简述


发布于 2024-04-12 / 102 阅读 / 0 评论 /
Javalin可以描述为A simple web framework for Java and Kotlin,很容易联想到Javalin=Java+(Kot)lin。

1.Javalin概述

官网对Javalin的介绍为:Javalin is a very lightweight web framework for Kotlin and Java which supports WebSockets, HTTP2 and async requests. Javalin’s main goals are simplicity, a great developer experience, and first class interoperability between Kotlin and Java。

简而言之,Javalin是一个轻量级的web框架,可用于kotlin和java开发,支持websocket、http2和async请求。

2.Javalin实战

基于Javalin框架的应用开发需要具备以下知识。

2.1.添加Maven依赖

基于Javalin框架进行开发的话,首先需要添加javalin依赖,如下所示:

<dependency>
    <groupId>io.javalin</groupId>
    <artifactId>javalin</artifactId>
    <version>5.6.1</version>
</dependency>

2.2.Main方法实现

然后是开发服务启动入口,实现main方法,例如下所示:

import io.javalin.Javalin;

public class HelloWorld {
    public static void main(String[] args) {
        Javalin app = Javalin.create().start(7000);
        app.get("/", ctx -> ctx.result("Hello World"));
    }
}

2.3.Api框架和服务器配置

如下所示:

val app = Javalin.create { config ->
    config.defaultContentType = "application/json"
    config.autogenerateEtags = true
    config.staticFiles.add("/public")
    config.asyncRequestTimeout = 10_000L
    config.dynamicGzip = true
    config.enforceSsl = true
}.routes {
    path("users") {
        get(UserController::getAll)
        post(UserController::create)
        path(":user-id") {
            get(UserController::getOne)
            patch(UserController::update)
            delete(UserController::delete)
        }
        ws("events", userController::webSocketEvents)
    }
}.start(port)

上述案例启动了服务器。并定义了对应的接口和协议类型。

2.4.Javalin使用websocket

Javalin支持对websocket接口的开发,例如下所示:

app.ws("/websocket/:path") { ws ->
    ws.onConnect { ctx -> println("Connected") }
    ws.onMessage { ctx ->
        val user = ctx.message<User>(); // convert from json string to object
        ctx.send(user); // convert to json string and send back
    }
    ws.onClose { ctx -> println("Closed") }
    ws.onError { ctx -> println("Errored") }
}

2.5.使用Filters和Mappers

例如下所示:

app.before("/some-path/*") { ctx ->  ... } // runs before requests to /some-path/*
app.before { ctx -> ... } // runs before all requests
app.after { ctx -> ... } // runs after all requests
app.exception(Exception.class) { e, ctx -> ... } // runs if uncaught Exception
app.error(404) { ctx -> ... } // runs if status is 404 (after all other handlers)

app.wsBefore("/some-path/*") { ws ->  ... } // runs before ws events on /some-path/*
app.wsBefore { ws -> ... } // runs before all ws events
app.wsAfter { ws -> ... } // runs after all ws events
app.wsException(Exception.class) { e, ctx -> ... } // runs if uncaught Exception in ws handler

2.6.通过Json配置接口

除了通过Java代码显示定义接口,我们还可以通过Javalin来实现json定义接口,案例如下:

var todos = arrayOf(...)
app.get("/todos") { ctx -> // map array of Todos to json-string
    ctx.json(todos)
}
app.put("/todos") { ctx -> // map request-body (json) to array of Todos
    todos = ctx.body<Array<Todo>>()
    ctx.status(204)
}

2.7.Javalin实现文件上传接口

案例如下所示:

app.post("/upload") { ctx ->
    ctx.uploadedFiles("files").forEach { (contentType, content, name, extension) ->
        FileUtil.streamToFile(content, "upload/$name")
    }
}

3.注意事项

Javalin框架中,service和dao层的开发与spring框架一致,只是不能使用annotation。