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.
category | value |
---|---|
os | windows 10 home 64bit |
Java | 1.8 |
framework | Javalin 3.6 |
Development environment | IntelliJ IDEA 2019.2 |
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"));
}
}
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.
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.
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
Once you know this, you can create a web application by looking at Docs and Tutorial.
Notes when examining Javalin nodchip's diary-Apache Commons DbUtils
Recommended Posts