Giter Site home page Giter Site logo

javalin / javalin.github.io Goto Github PK

View Code? Open in Web Editor NEW
35.0 35.0 85.0 10.55 MB

Javalin website source code

Home Page: https://javalin.io

Batchfile 0.08% Ruby 0.12% HTML 34.05% CSS 12.54% JavaScript 21.79% SCSS 24.50% Dockerfile 0.21% Java 3.84% Kotlin 2.89%

javalin.github.io's Introduction

Logo

A simple web framework for Java and Kotlin


Static Badge Stable Version Snapshot Version Discord Link

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 is more of a library than a framework. Some key points:

  • You don't need to extend anything
  • There are no @Annotations
  • There is no reflection
  • There is no other magic; just code.

General information

Community

We have a very active Discord server where you can get help quickly. We also have a (much less active) Slack if you prefer that.

Contributions are very welcome, you can read more about contributing in our guide: CONTRIBUTING

Please consider ❤️ Sponsoring or starring Javalin if you want to support the project.

Quickstart

Add dependency

Maven

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

Gradle

implementation("io.javalin:javalin:6.1.3")

Start programming (Java)

import io.javalin.Javalin;

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

Start programming (Kotlin)

import io.javalin.Javalin

fun main() {
    val app = Javalin.create(/*config*/)
        .get("/") { it.result("Hello World") }
        .start(7070)
}

Examples

This section contains a few examples, mostly just extracted from the docs. All examples are in Kotlin, but you can find them in Java in the documentation (it's just syntax changes).

You can find more examples in the javalin-samples repository.

Api structure and server config

import io.javalin.Javalin
import io.javalin.apibuilder.ApiBuilder.*

fun main() {
    val app = Javalin.create { config ->
        config.useVirtualThreads = true
        config.http.asyncTimeout = 10_000L
        config.staticFiles.add("/public")
        config.staticFiles.enableWebjars()
        config.router.apiBuilder {
            path("/users") {
                get(UserController::getAll)
                post(UserController::create)
                path("/{userId}") {
                    get(UserController::getOne)
                    patch(UserController::update)
                    delete(UserController::delete)
                }
                ws("/events", userController::webSocketEvents)
            }
        }
    }.start(7070)
}

WebSockets

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") }
}

Filters and 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

JSON-mapping

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)
}

File uploads

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

Plugins

Javalin has a plugin system that allows you to add functionality to the core library. You can find a list of plugins here.

Installing a plugin is as easy as adding a dependency to your project and registering it with Javalin:

Javalin.create { config ->
    config.registerPlugin(MyPlugin())
}

Some of the most popular plugins are:

OpenAPI Plugin

The Javalin OpenAPI plugin allows you to generate an OpenAPI 3.0 specification for your API at compile time.

Annotate your routes with @OpenApi to generate the specification:

@OpenApi(
    summary = "Get all users",
    operationId = "getAllUsers",
    tags = ["User"],
    responses = [OpenApiResponse("200", [OpenApiContent(Array<User>::class)])],
    path = "/users",
    methods = [HttpMethod.GET]
)
fun getAll(ctx: Context) {
    ctx.json(UserService.getAll())
}

Swagger UI and ReDoc UI implementations for viewing the generated specification in your browser are also available.

For more information, see the Javalin OpenAPI Wiki.

SSL Plugin

The Javalin SSL plugin allows you to easily configure SSL for your Javalin server, supporting a variety of formats such as PEM, PKCS12, DER, P7B, and JKS.

Enabling SSL on the 443 port is as easy as:

val plugin = SSLPlugin { conf ->
    conf.pemFromPath("/path/to/cert.pem", "/path/to/key.pem")
}

Javalin.create { javalinConfig ->
    javalinConfig.plugins.register(plugin)
}.start()

Sponsors

Special thanks

javalin.github.io's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

javalin.github.io's Issues

Possible additional info for Get Started doc using Kotlin Gradle.

Describe the bug

Ruby dev. New to Kotlin. Prototyping business need.
Using Intellij created a new Kotlin project using Gradle build with starting code.
Cut & Pasted the Javalin dependency for Gradle as described in Getting Started.
Received formatting errors from Intellij IDE.
Seems i needed to format as: implementation ("io.javalin:javalin-bundle:4.6.4")

Being my first Kotlin project (ok 2nd after hello world), maybe something i did setting project options (yes it was)?
Don't know if anyone else may hit this issue and if new to Gradle (like me) might get stuck for a few.

P.S. (added later) I just noticed/learned that u show the Groovy Gradle format. And i am using the Kotlin Gradle format. So i changed the title of this.

Coming from Ruby/Sinatra, like what i see in docs... thx...

Hello World not working

I like Javalin and try to get the Hello World going. According to the doc only javalin-2.5.0.jar is sufficient.

However, when I run the example I get the error:

run:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
	at io.javalin.Javalin.<clinit>(Javalin.java:54)
	at javalin.HelloWorld.main(HelloWorld.java:7)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 2 more
C:\Users\bergtwvd\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

I added slf4j-simple-1.7.25.jar to the CLASSPATH, but this did not make any difference.

Using JDK 1.8

-- TvdB

[PLUGIN REPORTS] - GraphQL

!!! The comments on this issue are reflected on https://javalin.io/plugins !!!

This is intended as safety mechanism to warn other users if a plugin is not behaving as it should.

Please be elaborate in your reports, and explain why there is a problem with the plugin.

[PLUGIN REPORTS] - Micrometer

!!! The comments on this issue are reflected on https://javalin.io/plugins !!!

This is intended as safety mechanism to warn other users if a plugin is not behaving as it should.

Please be elaborate in your reports, and explain why there is a problem with the plugin.

Include both Kotlin and Java versions on the Official Tutorials

[This issue is more of a reference of the one I made on the main Javalin Repo, it's just that this one's on the right place now, see this]

Currently what we have with the docs are two separated categories for the tutorials, one for Java and one for Kotlin:
image

I think it would be best if we only had one column that tackles each topic separately, but includes both the "Java" and "Kotlin" version on the same page.
image
Something like this one that toggles the code snippet into the version chosen by the user. This way, users who prefer a certain flavor can easily have access to tutorials that are fitted to what they currently know. Although Kotlin and Java do share a lot of similarities with each other, it would be nice to ease the burden to new users of the framework of having to learn and understand the other, just to be able to try things out. 😄

Write a better "Simple Kotlin Example" tutorial.

Current one is aimed at Java devs and was written the first day I tried out Kotlin. We should make one that's more to the point, just for Kotlin users. Rename the old one to "Kotlin for Java developers" or something.

Newbie issue: import io.javalin.ApiBuilder.*

Hello,

This was a small frustration I had following the tutorial, no explicit mention of what imports were required to remove errors when building the project. I went to the source code to fix the problem, but intellij did not know where to import the get/post/patch methods from!

It may make it easier for other beginners to test the project.

Handler groups not compiling

I suspect the problem here may be related to my particular configuration, but the handler groups example code fails to compile for me. The name app methods like path and get and post are not found, it does not seem to reference an implicit `app.

I'm using the JDK for Java 8, does this code depend on a newer version of Java?

Sponsors on website

@barbarysoftware thank you for your donation! Since you're on the $50 tier, you can have your logo present in the "Sponsors" section of the https://javalin.io, as well as a link to your website. Currently, this section doesn't exist (since you're the first $50 sponsor), but if you add your logo/link to this issue, I will create a section for it on the website :)

Tutorial Idea - Simple Tutorial

Hi!

Javalin seems very interesting and I would like to learn more about it.

I am quite to programming (work in engineering) and APIs. It would be nice to have a very simple (for beginners with only the very basics of programming) Java-based tutorial of how to use Javalin. I think the tutorials are great but quite complex for complete dummies.

For example, a small Java-program that reads the temperature in London (or any other information) of one website and prints it to the screen. Just something I could copy and paste directly in Eclipse and run it. In this way, I could get an easy start with Javalin.

I think such example would help many newcomers to start with Javalin.

Thank you very much!

User Session management?

I see there are function about Session in the Context, but it is not clear to me how you would create a session, store/retrieve data from the user session, delete the session, renew the session, expire ...

By the way, is there a user group like a Google Group or else ??? or Github issue is THE user group ?
Thanks

Can't display Chinese.

  1. Set "Properties > Resource > Text file encoding " to UTF-8
  2. Set the "properties" of "project.build.sourceEncoding", "maven.compiler.encoding" to UTF-8, in pom.xml

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>

Still can not display the Chinese word?

[PLUGIN REPORTS] - Cors Plugin

!!! The comments on this issue are reflected on https://javalin.io/plugins !!!

This is intended as safety mechanism to warn other users if a plugin is not behaving as it should.

Please be elaborate in your reports, and explain why there is a problem with the plugin.

[PLUGIN REPORTS] - RouteOverview

!!! The comments on this issue are reflected on https://javalin.io/plugins !!!

This is intended as safety mechanism to warn other users if a plugin is not behaving as it should.

Please be elaborate in your reports, and explain why there is a problem with the plugin.

[PLUGIN REPORTS] - JavalinMithril

!!! The comments on this issue are reflected on https://javalin.io/plugins !!!

This is intended as safety mechanism to warn other users if a plugin is not behaving as it should.

Please be elaborate in your reports, and explain why there is a problem with the plugin.

Heroku tutorial's future

Heroku will stop offering a free tier starting 2022-11-28.

Starting October 26, 2022, we will begin deleting inactive accounts and associated storage for accounts that have been inactive for over a year.

Starting November 28, 2022, we plan to stop offering free product plans and plan to start shutting down free dynos and data services. We will be sending out a series of email communications to affected users.

Our Heroku tutorial should be migrated to a different provider, ideally not requiring a credit card for easier testing for people without one or those who do not want to provide their credit card.

Add our logo and link to the Sponsors page

We're very pleased to be able to sponsor Javalin. We've just finished converting our app from Spark to Javalin.

The sponsorship is from my company, Barbary Software. However, we'd prefer the logo to be that of our main product, Feature Upvote.

Name: Feature Upvote
URL: https://featureupvote.com/
Logo: Our logos are here. You can select the one that works best for you.

Let me know if you need more info.

Highlight selected page in menu

Currently, when we're browsing site, we don't know which page is selected from the menu:

obraz

obraz

Would be nice if selected page had some indicator, like e.g.:

obraz

[PLUGIN REPORTS] - JavalinVue

!!! The comments on this issue are reflected on https://javalin.io/plugins !!!

This is intended as safety mechanism to warn other users if a plugin is not behaving as it should.

Please be elaborate in your reports, and explain why there is a problem with the plugin.

Who's using Javalin?

I added a "Who's using Javalin?" section on the webpage. The initial list is based on publicly available information from GitHub/Gitlab, Maven, and user websites.

If you want your company added to the list, please comment on this issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.