Spring Boot 2 MVC Web应用程序Thymeleaf JPA MySQL示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(9.5k)|赞(0)|评价(0)|浏览(363)

在这篇文章中,我们将学习如何使用Spring boot 2, Thymeleaf, Hibernate 5, JPA, Maven, and MySQL数据库开发一个Spring MVC Web应用程序。

1. 我们将创建什么

我们将使用Thymeleaf作为视图来构建一个简单的Spring MVC Web应用程序。

**输出。  **使用Thymeleaf的HTML页面,显示来自MySQL数据库的用户列表。

2. 使用的工具和技术

*Spring Boot - 2.0.4.RELEASE

  • JDK - 1.8或更高版本
  • Spring Framework - 5.0.8 RELEASE
  • Hibernate - 5.2.17.Final
  • Maven - 3.2以上版本
  • IDE - Eclipse 或 Spring Tool Suite (STS)
  • Tomcat - 8.5+
  • Thymeleaf
  • MySQL - 5.1.46

3. 创建和导入一个项目

创建Spring Boot应用程序的方法有很多。最简单的方法是在http://start.spring.io/使用Spring Initializr,它是一个在线Spring Boot应用程序生成器。

看上面的图,我们指定了以下细节。

Generate。Maven项目
Java版本。1.8 (默认)
Spring Boot:2.0.4
: net.guards.springboot2
Artifact: springboot2-webapp-thymeleaf
名称: springboot2-webapp-thymeleaf
包装名称 : net.guards.springboot2.springboot2webappthymeleaf
包装: jar (这是默认值)
依赖性: Web, JPA, MySQL, DevTools, Thymeleaf

一旦,所有的细节都被输入,点击生成项目按钮将生成一个spring boot项目并下载。接下来,解压下载的压缩文件并将其导入你最喜欢的IDE。

4. 包装结构

一旦我们在IDE中导入spring boot项目,我们将看到一些自动生成的文件。

  1. pom.xml
    1.资源
  2. Springboot2WebappThymeleafApplication.java
  3. Springboot2WebappThymeleafApplicationTests.java

The pom.xml File

<?xmlversion="1.0"encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>

     <groupId>net.guides.springboothelloworld</groupId>
     <artifactId>springboot2-webapp-thymeleaf</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <packaging>jar</packaging>

     <name>springboot2-webapp-thymeleaf</name>
     <description>Demo project for Spring Boot</description>

     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>2.0.4.RELEASE</version>
         <relativePath /> <!-- lookup parent from repository -->
     </parent>

     <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
          <java.version>1.8</java.version>
     </properties>

     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
        </dependency>
        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-devtools</artifactId>
             <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
             <groupId>com.h2database</groupId>
             <artifactId>h2</artifactId>
        </dependency>
     </dependencies>

     <build>
          <plugins>
              <plugin>
                   <groupId>org.springframework.boot</groupId>
                   <artifactId>spring-boot-maven-plugin</artifactId>
              </plugin>
          </plugins>
     </build>
 </project>

从上面的pom.xml中,我们可以了解一些重要的spring boot特性。

Spring Boot Maven插件

Spring Boot Maven插件提供了许多便利的功能。

  • 它收集classpath上的所有jar,并构建一个单一的、可运行的 "über-jar",这使得执行和传输你的服务更加方便。
  • 它搜索公共静态void main()method,以标记为可运行类。
  • 它提供了一个内置的依赖性解析器,可以设置版本号以匹配Spring Boot的依赖性。你可以覆盖你想要的任何版本,但它将默认为Boot选择的版本集。

spring-boot-starter-parent

所有Spring Boot项目通常在pom.xml中使用spring-boot-starter-parent作为父级。

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

父级Pom允许你为多个子项目和模块管理以下事项。

  • 配置 - Java版本和其他属性
  • 依赖性管理 - 依赖性的版本
  • 默认插件配置

简单的依赖性管理

我们添加了thespring-boot-starter-webdependency,在开发Spring MVC应用程序时,它将默认提取所有常用的库,如spring-webmvc、jackson-json、validation-api和Tomcat。

我们添加了thespring-boot-starter-data-jpadependency。这拉出了所有的spring-data-jpa依赖项,并添加了Hibernate库,因为大多数应用程序使用Hibernate作为JPA实现。

自动配置

Thespring-boot-starter-webadd所有这些库,而且它还用合理的默认值配置常用的注册Bean,如DispatcherServlet、ResourceHandlers、MessageSource等。

嵌入式Servlet容器支持

我们添加了spring-boot-starter-web,它可以自动拉动sspring-boot-starter-tomcatautatically。当我们运行themain()method时,它启动tomcat作为一个嵌入式容器,这样我们就不必在任何外部安装的tomcat服务器上部署我们的应用程序。如果我们想使用Jetty服务器而不是Tomcat呢?你只需将espring-boot-starter-tomcatf从spring-boot-starter-web中排除,并将espring-boot- starter-jetty包括在内。就这样了。

4.2. resources/

这个目录,顾名思义,专门存放所有的静态资源、模板和属性文件。

  • resources/static - 包含静态资源,如CSS、js和图片。
  • resources/templates - 包含服务器端的模板,由Spring渲染。
  • resources/application.properties - 这个文件非常重要。它包含应用程序范围内的属性。Spring会读取这个文件中定义的属性来配置你的应用程序。你可以在这个文件中定义服务器的默认端口、服务器的上下文路径、数据库URLs等。

5. Springboot2WebappThymeleafApplication.java文件

这个类提供了一个入口,有*public static void main(String[] args)*方法,你可以运行它来启动应用程序。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot2WebappThymeleafApplication {

     public static void main(String[] args) {
          SpringApplication.run(Springboot2WebappThymeleafApplication.class, args);
     }
}

@SpringBootApplication是一个方便的注解,添加了以下所有内容。

  • @Configuration将该类标记为应用程序上下文的Bean定义的来源。
  • @EnableAutoConfiguration告诉Spring Boot开始根据classpath设置、其他bean和各种属性设置来添加bean。
    *通常你会为Spring MVC应用添加@EnableWebMvc f,但Spring Boot在classpath上看到spring-webmvc时,会自动添加它。这标志着该应用是一个Web应用,并激活了一些关键行为,如设置DispatcherServlet
  • @ComponentScan告诉Spring寻找hello包中的其他组件、配置和服务,使其能够找到控制器。
    main()方法使用Spring Boot的SpringApplication.run()方法来启动一个应用程序。你是否注意到,没有一行XML?也没有web.xml文件。这个Web应用程序是100%的纯Java,你不需要处理配置任何管道或基础设施。

6. 创建一个名为User.java的JPA实体

package net.guides.springboot2.springboot2webappthymeleaf.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User
{
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
 
    public User()
    {
    }

    public User(Integer id, String name)
    {
         this.id = id;
         this.name = name;
    }

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

7. 创建Spring Data JPA存储库 - UserRepository.java

package net.guides.springboot2.springboot2webappthymeleaf.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import net.guides.springboot2.springboot2webappthymeleaf.domain.User;

public interface UserRepository extends JpaRepository<User, Integer>
{

}

8. 创建Spring控制器 - HomeController.java

package net.guides.springboot2.springboot2webappthymeleaf.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import net.guides.springboot2.springboot2webappthymeleaf.repositories.UserRepository;

@Controller
public class HomeController
{
    @Autowired UserRepository userRepo;
 
    @RequestMapping("/")
    public String home(Model model)
    {
        model.addAttribute("users", userRepo.findAll());
        return "index";
    }
}

9. 配置MySQL数据库

配置application.properties以连接到你的MySQL数据库。让我们打开一个application.properties文件,并在其中添加以下数据库配置。

logging.level.org.springframework=INFO

################### DataSource Configuration ##########################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/users_database
spring.datasource.username=root
spring.datasource.password=root

################### Hibernate Configuration ##########################

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Spring boot 2.0.4 RELEASE internally uses below MySQL version in pom.xml:
 
 <mssql-jdbc.version>6.2.2.jre8</mssql-jdbc.version>
 
 <mysql.version>5.1.46</mysql.version>

message.properties

app.title=SpringMVC JPA Demo (With SpringBoot)

要了解更多,请参考我的GitHub repository上的源代码。

10. 插入SQL脚本

一旦你运行这个应用程序,将在数据库中创建用户表,并使用下面的插入SQL脚本在用户表中填充一些记录。

INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('1', 'Salman');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('2', 'SRK');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('3', 'AMIR');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('4', 'Tiger');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('5', 'Prabhas');

11. 创建一个Thymeleaf视图 - index.html

让我们创建一个Thymeleaf视图来显示用户的列表。在本项目的src/main/resources/templates文件夹下找到index.html文件。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
   xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Home</title>
</head>
<body>
 <h2 th:text="#{app.title}">App Title</h2>
    <table>
        <thead>
         <tr>
           <th>Id</th>
           <th>Name</th>
        </tr>
        </thead>
        <tbody>
          <tr th:each="user : ${users}">
             <td th:text="${user.id}">Id</td>
             <td th:text="${user.name}">Name</td>
          </tr>
        </tbody>
    </table>
</body>
</html>

12. 运行应用程序

现在将Springboot2WebappThymeleafApplication.java作为一个Java应用程序运行,将浏览器指向http://localhost:8080/。 

你会在屏幕上看到下面的HTML页面。

12. GitHub上的源代码

本教程的源代码可在我的GitHub存储库中找到。

Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example

相关文章

微信公众号

最新文章

更多