Build a web application with Javalin

I've tried a framework called Javalin, so I'll post it.

This framework has little information such as reference books and Japanese sites, but Docs and Tutorial are very easy to understand, especially in Tutorial, sample programs are posted on GitHUB, so import them as they are in Intellij. You can customize it, so you won't have much trouble creating a WEB application.

environment

category value
os windows 10 home 64bit
Java 1.8
framework Javalin 3.6
Development environment IntelliJ IDEA 2019.2
  1. Hello World

Just create a new Gradle project and implement: If Java is installed, Web Server will also start. You don't even need Tomcat.

HelloWorld.java


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"));
    }
}
  1. Tutorial(Basic website structure)

In practice, a good approach would be to download and customize the Tutorial sample program. Download the "Basic website structure" tipsy / javalin-website-example and open it in Intellij.

project.tree


└─src
    └─main
        ├─java
        │  └─app
        │      │  Main.java
        │      ├─book
        │      │      Book.java
        │      │      BookController.java
        │      │      BookDao.java
        │      ├─index
        │      │      IndexController.java
        │      ├─login
        │      │      LoginController.java
        │      ├─user
        │      │      User.java
        │      │      UserController.java
        │      │      UserDao.java
        │      └─util
        │              Filters.java
        │              HerokuUtil.java
        │              MessageBundle.java
        │              Path.java
        │              RequestUtil.java
        │              ViewUtil.java
        └─resources
            ├─localization
            │      messages_de.properties
            │      messages_en.properties
            ├─public
            │  │  main.css
            │  └─img
            │          english.png
            │          favicon.png
            │          german.png
            │          logo.png
            ├─velocity
            │  │  layout.vm
            │  │  notFound.vm
            │  ├─book
            │  │      all.vm
            │  │      one.vm
            │  ├─index
            │  │      index.vm
            │  └─login
            │          login.vm
            └─velocityconfig
                    velocity_implicit.vm

If you execute Main, it will work as it is. All you have to do is convert a class such as DAO to a database and you can create a project template.

  1. Thymeleaf

The template engine of the project you just imported is "velocity". If you want to use Thymeleaf, you need to change it. "Javalin" seems to support thymeleaf by default, but it doesn't seem to support dialect, so let's customize it.

The root of html is "/ public / templates". Create a file with the following configuration. In layout.html, use layout-dialect to standardize the html layout.

└─src
    ├─main
    │  ├─java
    │  │  └─app
    │  │          AppThymeleafRenderer.java
    │  │          Main.java
    │  └─resources
    │      ├─public
    │      │  └─css
    │      │         main.css
    │      └─templates
    │          │  layout.html
    │          └─example
    │                  index.html

(1) Add the following to gradle.gradle.

    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.11.RELEASE'
    compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '2.4.1'
    compile "org.webjars:jquery:3.4.1"

(2) ThymeleafRenderer

Thymeleaf needs to create its own renderer when customizing, such as when using "layout-dialect".

AppThymeleafRenderer.java



import io.javalin.http.Context;
import io.javalin.plugin.rendering.FileRenderer;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.jetbrains.annotations.NotNull;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.util.Map;

public class AppThymeleafRenderer implements FileRenderer {

    private final TemplateEngine templateEngine;

    public AppThymeleafRenderer() {
        templateEngine = templateEngine();
    }

    @Override
    public String render(@NotNull String filePath, @NotNull Map<String, Object> model, @NotNull Context ctx) {
        WebContext context =
                new WebContext(ctx.req, ctx.res, ctx.req.getServletContext(), ctx.req.getLocale());
        context.setVariables(model);
        return templateEngine.process(filePath, context);
    }

    private TemplateEngine templateEngine() {
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        //Add LayoutDialect.
        templateEngine.addDialect(new LayoutDialect());
        return templateEngine;
    }

    private ITemplateResolver templateResolver() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        // /Root the templates folder.
        templateResolver.setPrefix("/templates/");
        return templateResolver;
    }

}

(3) Added to Main.java

In the Main method, add the "AppThymeleafRenderer" class created earlier to "JavalinRenderer". Also, if you want to return html with Router, use "ctx.render".

Main.java



public class Main {
    public static void main(String[] args) {

//add
        JavalinRenderer.register(new AppThymeleafRenderer(), ".html");
//add end
        Javalin app = Javalin.create(config->{
            config.enableWebjars();
            config.addStaticFiles("/public");
        }).start(7000);
//add
        app.get("/template", ctx -> {
            Map<String, Object> model = new HashMap<>();
            model.put("hello", "hello world");
            ctx.render("/example/index.html", model);
        });
//add end

(4) layout.html

layout.html


<!DOCTYPE html>
<html lang="ja" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <title>Spring Boot Sample Site</title>
    <meta name="description" content="common-meta">
    <script th:src="@{/webjars/jquery/3.4.1/jquery.min.js}"></script>
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
    <div class="inner">
        <div class="body header">
            <div class="apptitle">Example</div>
        </div>
        <div class="body main">
            <div layout:fragment="contents"></div>
        </div>
        <div class="body footer">
            <footer style="text-align:center;">Common footer</footer>
        </div>
    </div>
</div>
</body>
</html>

index.html


<!DOCTYPE html>
<html
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{/layout.html}">
<head></head>
<body>
<div layout:fragment="contents">
    <div th:text="${hello}">hello</div>
</div>
</body>
</html>

When I access [http: // localhost: 7000 / template](http: // localhost: 7000 / template), layout is also output correctly.

image.png

  1. Database

After a lot of trouble, I decided to use "Apache commons-dbutils". The reason is simply easy to understand. Use "HikariCP" for the Connection Pool and "postgresql" for the Database.

build.gradle


    compile "com.zaxxer:HikariCP:2.7.3"
    compile "org.postgresql:postgresql:42.2.8"
    compile "commons-dbutils:commons-dbutils:1.7"

PGDataSource.java



import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;

public class PGDataSource {
    private static HikariDataSource ds = null;
    public PGDataSource(){
        HikariConfig hikariconfig = new HikariConfig();
        hikariconfig.setUsername("testuser");
        hikariconfig.setPassword("************************");
        hikariconfig.setJdbcUrl("jdbc:postgresql://localhost:5432/javalindb");
        hikariconfig.setMaximumPoolSize(2);
        ds=new HikariDataSource(hikariconfig);
    }
    public DataSource getDataSource(){
        return ds;
    }
    public void close(){
        if (!ds.isClosed()) ds.close();
    }

}

User.java


import lombok.Data;

@Data
public class User {
    private String username;
    private String password;
    public User(){};
    public User(String username, String password){
        this.username=username;
        this.password=password;
    };
}

Main.java


public class Main {

//add
    private static PGDataSource ds;
    public static Connection getConnection() throws SQLException {
        Connection connection = ds.getDataSource().getConnection();
        return connection;
    }
//add end
    public static void main(String[] args) {
        JavalinRenderer.register(new AppThymeleafRenderer(), ".html");
//add
        ds = new PGDataSource();
//add end
//・ ・ ・ ・ ・ ・ ・
//add
        app.get("/user", ctx -> {
            QueryRunner runner = new QueryRunner();
            ResultSetHandler rsh = new BeanListHandler(User.class);
            List<User> users = (List<User>) runner.query(getConnection(),
                    "select username from public.users",rsh);
            ctx.json(users);
        });
//add end

image.png

Once you know this, you can create a web application by looking at Docs and Tutorial.

5. Reference site

Notes when examining Javalin nodchip's diary-Apache Commons DbUtils

Recommended Posts

Build a web application with Javalin
Create a simple web application with Dropwizard
Build a WEB system with Spring + Doma + H2DB
Web application built with docker (1)
Build a WEB system with Spring + Doma + H2DB + Thymeleaf
Build a WEB system with Spring + Doma + H2DB Part 2
Build a Java project with Gradle
Build a Node.js environment with Docker
Build a Tomcat 8.5 environment with Pleiades 4.8
The first WEB application with Spring Boot-Making a Pomodoro timer-
Until you create a Web application with Servlet / JSP (Part 1)
Try developing a containerized Java web application with Eclipse + Codewind
Web application creation with Nodejs with Docker
Let's make a book management web application with Spring Boot part1
Let's make a book management web application with Spring Boot part3
Let's make a book management web application with Spring Boot part2
I want to develop a web application!
Build a PureScript development environment with Docker
Start web application development with Spring Boot
Build a Wordpress development environment with Docker
De-cron! Build a job scheduler with Rundeck
Run WEB application with Spring Boot + Thymeleaf
Build Web Application Server (Java) on VPS
Build a Windows application test environment with Selenium Grid, Appium, and Windows Application Driver
Creating a java web application development environment with docker for mac part1
I tried to build a Firebase application development environment with Docker in 2020
[Java] Deploy a web application created with Eclipse + Maven + Ontology on Heroku
Create a java web application development environment with docker for mac part2
Build a web application development environment that uses Java, MySQL, and Redis with Docker CE for Windows
# 1 [Beginner] Create a web application (website) with Eclipse from knowledge 0. "Let's build an environment for creating web applications"
Build a Laravel / Docker environment with VSCode devcontainer
Build a WordPress development environment quickly with Docker
[Win10] Build a JSF development environment with NetBeans
Create a web api server with spring boot
Build a Java development environment with VS Code
I tried to clone a web application full of bugs with Spring Boot
Build a docker container for a python simple web server
[Tutorial] Download Eclipse → Run Web application with Java (Pleiades)
Build Doma1 with Ant
Easily build a Vue.js environment with Docker + Vue CLI
java build a triangle
[Personal application work memo] Make a calendar with simple_calendar
[Note] Build a Python3 environment with Docker in EC2
Web application test automation
Build Growai with Centos7
Roughly the flow of web application development with Rails.
A story that stumbled when deploying a web application created with Spring Boot to EC2
Create a JAVA WEB application and try OMC APM
[Environment construction] Build a Java development environment with VS Code!
Build Java with Wercker
Build bazel with alpine
[Review] When creating a web application with Rails, syntax error, unexpected')', expecting => ...]}% ","% # {params [: content]}% "]) ...
Story of making a task management application with swing, java
I tried to modernize a Java EE application with OpenShift.
Web application development memo with MVN, Tomcat, JSP / Servlet with VScode
From studying programming for 2 months to releasing a web application
Check the operation of two roles with a chat application
Create a Hello World web app with Spring framework + Jetty
Java web application development environment construction with VS Code (struts2)
Build a "Spring Thorough Introduction" development environment with IntelliJ IDEA
A memo to build Jitsi Meet on Azure with docker-compose