qute的简单使用
1.环境说明
1 2 3
| Java:17.0.8 Quarkus:3.4.2 Maven:3.9.5
|
2.添加依赖
1 2 3 4
| <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy-reactive-qute</artifactId> </dependency>
|
3.测试
3.1.Item.java
1 2 3 4 5 6 7 8 9 10 11 12 13
| import java.math.BigDecimal;
public class Item {
public final BigDecimal price; public final String name;
public Item(BigDecimal price, String name) { this.price = price; this.name = name; }
}
|
3.2.HelloResource.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import org.jboss.resteasy.reactive.RestQuery;
import io.quarkus.qute.Template; import io.quarkus.qute.TemplateInstance;
@Path("/hello") public class HelloResource {
@Inject Template hello;
@GET @Produces(MediaType.TEXT_HTML) public TemplateInstance get(@RestQuery String name) { return hello.data("name", name); }
}
|
3.3.ItemResource.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import java.math.BigDecimal; import java.util.ArrayList; import java.util.List;
import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType;
import io.quarkus.qute.CheckedTemplate; import io.quarkus.qute.TemplateExtension; import io.quarkus.qute.TemplateInstance;
@Path("items") public class ItemResource {
@CheckedTemplate static class Templates {
static native TemplateInstance items(List<Item> items); }
@GET @Produces(MediaType.TEXT_HTML) public TemplateInstance get() { List<Item> items = new ArrayList<>(); items.add(new Item(new BigDecimal(10), "Apple")); items.add(new Item(new BigDecimal(16), "Pear")); items.add(new Item(new BigDecimal(30), "Orange")); return Templates.items(items); }
@TemplateExtension static BigDecimal discountedPrice(Item item) { return item.price.multiply(new BigDecimal("0.9")); }
}
|
3.4.hello.html
1 2 3 4 5 6 7 8 9 10
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Qute Hello World</title> </head> <body> <p>Hello {name ?: "world"}!</p> </body> </html>
|
3.5.items.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Qute - Items</title> </head> <body> <h1>List of Items</h1> <ul> {#for item in items} <li> {item.name}: {#if item.price < 15} {item.price} {#else} <del>{item.price}</del> <strong>{item.discountedPrice}</strong> {/if} </li> {/for} </ul> </body> </html>
|
hello.html
和items.html
需要放在resources/templates
下面
启动项目访问:
http://localhost:80/items
http://localhost:80/hello