当前位置:   article > 正文

Spring Boot集成vaadin快速入门demo

Spring Boot集成vaadin快速入门demo

1.什么是vaadin?

Vaadin 是用于构建单页 Web 应用的流行 Java 框架。 它由一家专门从事富 Internet 应用设计和开发的芬兰公司开发。 估计有 15 万开发者使用 Vaadin。 它的开发始于 2002 年。

Vaadin 框架特性

以下是 Vaadin 特性的列表:

  • 这是一个 Java Web 框架
  • 概念上类似于 Java Swing
  • 允许构建不带 HTML 和 JavaScript 的 Web 应用
  • 基于 Java Servlet 构建
  • 包含大量组件和窗口
  • 提供可定制的外观
  • 在客户端和服务器之间使用异步消息
  • 使用服务器端编程模型
  • 具有 Eclipse,NetBeans 和 IntelliJ 的插件
  • 使用 Google Web Toolkit 呈现结果网页
  • 提升代码质量和安全性

2.代码工程

实验目标

嵌入式数据库h2存储数据,用vaadin构建crud操作界面,使用jpa操作h2数据库

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>3.3.0</version>
  9. <relativePath/>
  10. <!-- lookup parent from repository -->
  11. </parent>
  12. <modelVersion>4.0.0</modelVersion>
  13. <artifactId>vaadin</artifactId>
  14. <properties>
  15. <maven.compiler.source>17</maven.compiler.source>
  16. <maven.compiler.target>17</maven.compiler.target>
  17. <vaadin.version>24.3.13</vaadin.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-autoconfigure</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-test</artifactId>
  31. <scope>test</scope>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-data-jpa</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>com.vaadin</groupId>
  39. <artifactId>vaadin-spring-boot-starter</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>com.h2database</groupId>
  43. <artifactId>h2</artifactId>
  44. <scope>runtime</scope>
  45. </dependency>
  46. </dependencies>
  47. <dependencyManagement>
  48. <dependencies>
  49. <dependency>
  50. <groupId>com.vaadin</groupId>
  51. <artifactId>vaadin-bom</artifactId>
  52. <version>24.3.8</version> <!-- check latest version -->
  53. <type>pom</type>
  54. <scope>import</scope>
  55. </dependency>
  56. </dependencies>
  57. </dependencyManagement>
  58. </project>

view

主视图类(MainView本指南中称为)是 Vaadin 的 UI 逻辑的入口点。在 Spring Boot 应用程序中,如果您使用 对其进行注释@Route,它将自动被拾取并显示在 Web 应用程序的根目录中。您可以通过为注释提供参数来自定义显示视图的 URL @Route

  1. package com.et.vaadin.view;
  2. import com.et.vaadin.entity.Customer;
  3. import com.et.vaadin.repository.CustomerRepository;
  4. import com.vaadin.flow.component.button.Button;
  5. import com.vaadin.flow.component.grid.Grid;
  6. import com.vaadin.flow.component.icon.VaadinIcon;
  7. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  8. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  9. import com.vaadin.flow.component.textfield.TextField;
  10. import com.vaadin.flow.data.value.ValueChangeMode;
  11. import com.vaadin.flow.router.Route;
  12. import org.springframework.util.StringUtils;
  13. @Route
  14. public class MainView extends VerticalLayout {
  15. private final CustomerRepository repo;
  16. private final CustomerEditor editor;
  17. final Grid<Customer> grid;
  18. final TextField filter;
  19. private final Button addNewBtn;
  20. public MainView(CustomerRepository repo, CustomerEditor editor) {
  21. this.repo = repo;
  22. this.editor = editor;
  23. this.grid = new Grid<>(Customer.class);
  24. this.filter = new TextField();
  25. this.addNewBtn = new Button("New customer", VaadinIcon.PLUS.create());
  26. // build layout
  27. HorizontalLayout actions = new HorizontalLayout(filter, addNewBtn);
  28. add(actions, grid, editor);
  29. grid.setHeight("300px");
  30. grid.setColumns("id", "firstName", "lastName");
  31. grid.getColumnByKey("id").setWidth("50px").setFlexGrow(0);
  32. filter.setPlaceholder("Filter by last name");
  33. // Hook logic to components
  34. // Replace listing with filtered content when user changes filter
  35. filter.setValueChangeMode(ValueChangeMode.LAZY);
  36. filter.addValueChangeListener(e -> listCustomers(e.getValue()));
  37. // Connect selected Customer to editor or hide if none is selected
  38. grid.asSingleSelect().addValueChangeListener(e -> {
  39. editor.editCustomer(e.getValue());
  40. });
  41. // Instantiate and edit new Customer the new button is clicked
  42. addNewBtn.addClickListener(e -> editor.editCustomer(new Customer("", "")));
  43. // Listen changes made by the editor, refresh data from backend
  44. editor.setChangeHandler(() -> {
  45. editor.setVisible(false);
  46. listCustomers(filter.getValue());
  47. });
  48. // Initialize listing
  49. listCustomers(null);
  50. }
  51. // tag::listCustomers[]
  52. void listCustomers(String filterText) {
  53. if (StringUtils.hasText(filterText)) {
  54. grid.setItems(repo.findByLastNameStartsWithIgnoreCase(filterText));
  55. } else {
  56. grid.setItems(repo.findAll());
  57. }
  58. }
  59. // end::listCustomers[]
  60. }

由于 Vaadin UI 是纯 Java 代码,因此您可以从头开始编写可重复使用的代码。为此,请为您的Customer实体定义一个编辑器组件。您可以将其设为 Spring 管理的 bean,以便您可以直接将其注入CustomerRepository编辑器并处理创建、更新和删除部分或您的 CRUD 功能

  1. package com.et.vaadin.view;
  2. import com.et.vaadin.entity.Customer;
  3. import com.et.vaadin.repository.CustomerRepository;
  4. import com.vaadin.flow.component.button.Button;
  5. import com.vaadin.flow.component.grid.Grid;
  6. import com.vaadin.flow.component.icon.VaadinIcon;
  7. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  8. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  9. import com.vaadin.flow.component.textfield.TextField;
  10. import com.vaadin.flow.data.value.ValueChangeMode;
  11. import com.vaadin.flow.router.Route;
  12. import org.springframework.util.StringUtils;
  13. @Route
  14. public class MainView extends VerticalLayout {
  15. private final CustomerRepository repo;
  16. private final CustomerEditor editor;
  17. final Grid<Customer> grid;
  18. final TextField filter;
  19. private final Button addNewBtn;
  20. public MainView(CustomerRepository repo, CustomerEditor editor) {
  21. this.repo = repo;
  22. this.editor = editor;
  23. this.grid = new Grid<>(Customer.class);
  24. this.filter = new TextField();
  25. this.addNewBtn = new Button("New customer", VaadinIcon.PLUS.create());
  26. // build layout
  27. HorizontalLayout actions = new HorizontalLayout(filter, addNewBtn);
  28. add(actions, grid, editor);
  29. grid.setHeight("300px");
  30. grid.setColumns("id", "firstName", "lastName");
  31. grid.getColumnByKey("id").setWidth("50px").setFlexGrow(0);
  32. filter.setPlaceholder("Filter by last name");
  33. // Hook logic to components
  34. // Replace listing with filtered content when user changes filter
  35. filter.setValueChangeMode(ValueChangeMode.LAZY);
  36. filter.addValueChangeListener(e -> listCustomers(e.getValue()));
  37. // Connect selected Customer to editor or hide if none is selected
  38. grid.asSingleSelect().addValueChangeListener(e -> {
  39. editor.editCustomer(e.getValue());
  40. });
  41. // Instantiate and edit new Customer the new button is clicked
  42. addNewBtn.addClickListener(e -> editor.editCustomer(new Customer("", "")));
  43. // Listen changes made by the editor, refresh data from backend
  44. editor.setChangeHandler(() -> {
  45. editor.setVisible(false);
  46. listCustomers(filter.getValue());
  47. });
  48. // Initialize listing
  49. listCustomers(null);
  50. }
  51. // tag::listCustomers[]
  52. void listCustomers(String filterText) {
  53. if (StringUtils.hasText(filterText)) {
  54. grid.setItems(repo.findByLastNameStartsWithIgnoreCase(filterText));
  55. } else {
  56. grid.setItems(repo.findAll());
  57. }
  58. }
  59. // end::listCustomers[]
  60. }

entity

  1. package com.et.vaadin.entity;
  2. import jakarta.persistence.Entity;
  3. import jakarta.persistence.GeneratedValue;
  4. import jakarta.persistence.Id;
  5. @Entity
  6. public class Customer {
  7. @Id
  8. @GeneratedValue
  9. private Long id;
  10. private String firstName;
  11. private String lastName;
  12. protected Customer() {
  13. }
  14. public Customer(String firstName, String lastName) {
  15. this.firstName = firstName;
  16. this.lastName = lastName;
  17. }
  18. public Long getId() {
  19. return id;
  20. }
  21. public String getFirstName() {
  22. return firstName;
  23. }
  24. public void setFirstName(String firstName) {
  25. this.firstName = firstName;
  26. }
  27. public String getLastName() {
  28. return lastName;
  29. }
  30. public void setLastName(String lastName) {
  31. this.lastName = lastName;
  32. }
  33. @Override
  34. public String toString() {
  35. return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id,
  36. firstName, lastName);
  37. }
  38. }

repository

  1. package com.et.vaadin.repository;
  2. import com.et.vaadin.entity.Customer;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import java.util.List;
  5. /**
  6. * @author liuhaihua
  7. * @version 1.0
  8. * @ClassName CustomerRepository
  9. * @Description todo
  10. */
  11. public interface CustomerRepository extends JpaRepository<Customer, Long> {
  12. List<Customer> findByLastNameStartsWithIgnoreCase(String lastName);
  13. }

application.yaml

  1. server:
  2. port: 8088

DemoApplication.java

  1. package com.et.vaadin;
  2. import com.et.vaadin.entity.Customer;
  3. import com.et.vaadin.repository.CustomerRepository;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.boot.SpringApplication;
  8. import org.springframework.boot.autoconfigure.SpringBootApplication;
  9. import org.springframework.context.annotation.Bean;
  10. @SpringBootApplication
  11. public class DemoApplication {
  12. private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
  13. public static void main(String[] args) {
  14. SpringApplication.run(DemoApplication.class, args);
  15. }
  16. @Bean
  17. public CommandLineRunner loadData(CustomerRepository repository) {
  18. return (args) -> {
  19. // save a couple of customers
  20. repository.save(new Customer("Jack", "Bauer"));
  21. repository.save(new Customer("Chloe", "O'Brian"));
  22. repository.save(new Customer("Kim", "Bauer"));
  23. repository.save(new Customer("David", "Palmer"));
  24. repository.save(new Customer("Michelle", "Dessler"));
  25. // fetch all customers
  26. log.info("Customers found with findAll():");
  27. log.info("-------------------------------");
  28. for (Customer customer : repository.findAll()) {
  29. log.info(customer.toString());
  30. }
  31. log.info("");
  32. // fetch an individual customer by ID
  33. Customer customer = repository.findById(1L).get();
  34. log.info("Customer found with findOne(1L):");
  35. log.info("--------------------------------");
  36. log.info(customer.toString());
  37. log.info("");
  38. // fetch customers by last name
  39. log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
  40. log.info("--------------------------------------------");
  41. for (Customer bauer : repository
  42. .findByLastNameStartsWithIgnoreCase("Bauer")) {
  43. log.info(bauer.toString());
  44. }
  45. log.info("");
  46. };
  47. }
  48. }

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

3.测试

启动Spring Boot应用,

测试crud操作

访问地址http://127.0.0.1:8088/

vaadin-list

 

4.引用

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号