• Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example


    In this article, we will learn how to develop a Spring MVC web application using Spring boot 2, Thymeleaf, Hibernate 5, JPA, Maven, and MySQL database.

    Table of Contents

    1. What we’ll build
    2. Tools and Technologies Used
    3. Creating and Importing a Project
    4. Packaging Structure
    5. The Springboot2WebappThymeleafApplication.java File
    6. Create a JPA Entity called User.java
    7. Create Spring Data JPA Repository - UserRepository.java
    8. Create Spring Controller - HomeController.java
    9. Configuring MySQL Database
    10. Insert SQL Script
    11. Create a Thymeleaf View - index.html
    12. Running the Application
    13. Source Code on Github

    1. What we’ll build

    We are building a simple Spring MVC web application using Thymeleaf as a view.

    使用Thymeleaf作为视图构建一个简单的spring MVC Web应用程序

    Output: HTML page using Thymeleaf which displays a list of users from MySQL database.

    使用Thymeleaf的HTML页面,该页面显示MySQL数据库中的用户列表

    2. Tools and Technologies Used

    • Spring Boot - 2.3.2.RELEASE
    • JDK - 1.8 or later
    • Spring Framework - 5.0.8 RELEASE
    • Hibernate - 5.4.17.Final
    • Maven - 3.6+
    • Tomcat - 8.5+
    • Thymeleaf
    • MySQL - 8.0.20

    3. Creating and Importing a Project

    There are many ways to create a Spring Boot application. The simplest way is to use Spring Initializr at http://start.spring.io/, which is an online Spring Boot application generator.

    Look at the above diagram, we have specified following details:

    • Generate: Maven Project
    • Java Version: 1.8 (Default)
    • Spring Boot:2.3.2
    • Group: com.guides
    • Artifact: webapp-thymeleaf
    • Name: webapp-thymeleaf
    • Package Name : com.guides.webappthymeleaf
    • Packaging: jar (This is the default value)
    • Dependencies: Web, JPA, MySQL, DevTools, Thymeleaf

    Once, all the details are entered, click on Generate Project button will generate a spring boot project and downloads it. Next, Unzip the downloaded zip file and import it into your favorite IDE.

    4. Packaging Structure

    Once we have imported spring boot project in IDE, we will see some auto-generated files.

    1. pom.xml
    2. resources
    3. WebappThymeleafApplication.java
    4. WebappThymeleafApplicationTests.java

    The pom.xml File

    <?xml version="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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.3.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.guides</groupId>
        <artifactId>webapp-thymeleaf</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>webapp-thymeleaf</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>11</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.20</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    From above pom.xml, let's understand few important spring boot features.

    Spring Boot Maven plugin

    The Spring Boot Maven plugin provides many convenient features:

    • It collects all the jars on the classpath and builds a single, runnable "jar", which makes it more convenient to execute and transport your service.

      它收集类路径上的所有jar,并构建一个可运行的单个“jar”,这使执行和传输服务更加方便

    • It searches for the public static void main() method to flag as a runnable class.

      它搜索public static void main()方法以将其标记为可运行类

    • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.

      它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项。您可以覆盖所需的任何版本,但默认为Boot选择的一组版本

    spring-boot-starter-parent

    All Spring Boot projects typically use spring-boot-starter-parent as the parent in pom.xml.

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

    Parent Poms allow you to manage the following things for multiple child projects and modules:

    父Poms允许您管理多个子项目和模块的以下内容:

    • Configuration - Java Version and Other Properties

      配置-Java版本和其他属性

    • Dependency Management - Version of dependencies

      依赖管理-依赖版本

    • Default Plugin Configuration

      默认插件配置

    Easy Dependency Management

    轻松的依赖管理

    We added the spring-boot-starter-web dependency, it will by default pull all the commonly used libraries while developing Spring MVC applications, such as spring-webmvc, jackson-json, validation-api, and Tomcat.

    我们添加了spring-boot-starter-web依赖关系,默认情况下,它将在开发Spring MVC应用程序时提取所有常用的库,例如spring-webmvc,jackson-json,validation-api和Tomcat。

    We added the spring-boot-starter-data-jpa dependency. This pulls all the spring-data-jpa dependencies and adds Hibernate libraries because most applications use Hibernate as a JPA implementation.

    我们添加了spring-boot-starter-data-jpa依赖项。由于大多数应用程序都将Hibernate作为JPA实现,因此这会拉取所有的spring-data-jpa依赖关系并添加Hibernate库

    Autoconfiguration

    Not only does the spring-boot-starter-web add all these libraries but it also configures the commonly registered beans like DispatcherServlet, ResourceHandlers, MessageSource, etc. with sensible defaults.

    spring-boot-starter-web不仅添加了所有这些库,而且还使用合理的默认值配置了常用注册的Bean,例如DispatcherServlet,ResourceHandlers,MessageSource等

    Embedded Servlet Container Support

    嵌入式Servlet容器支持

    We added spring-boot-starter-web, which pulls spring-boot-starter-tomcat automatically. When we run the main() method, it starts tomcat as an embedded container so that we don’t have to deploy our application on any externally installed tomcat server. What if we want to use a Jetty server instead of Tomcat? You simply exclude spring-boot-starter-tomcat from spring-boot-starter-web and include spring-boot- starter-jetty. That’s it.

    我们添加了spring-boot-starter-web,它会自动拉出spring-boot-starter-tomcat。当我们运行main()方法时,它会将tomcat作为嵌入式容器启动,因此我们不必在任何外部安装的tomcat服务器上部署应用程序。如果我们要使用Jetty服务器而不是Tomcat怎么办?您只需将spring-boot-starter-tomcat从spring-boot-starter-web中排除,并包括spring-boot-starter-jetty

    4.2. resources/

    This directory, as the name suggests, is dedicated to all the static resources, templates and property files.

    顾名思义,该目录专用于所有静态资源,模板和属性文件

    • resources/static - contains static resources such as CSS, js, and images.

      包含静态资源,例如CSS,js和图像

    • resources/templates - contains server-side templates which are rendered by Spring.

      包含由Spring呈现的服务器端模板

    • resources/application.properties - This file is very important. It contains application-wide properties. Spring reads the properties defined in this file to configure your application. You can define a server’s default port, server’s context path, database URLs etc, in this file.

      这个文件非常重要。它包含应用程序范围的属性。Spring读取此文件中定义的属性以配置您的应用程序。您可以在此文件中定义服务器的默认端口,服务器的上下文路径,数据库URL等。

    5. The WebappThymeleafApplication.java File

    This class provides an entry point with the public static void main(String[] args) method, which you can run to start the application.

    package com.guides.webappthymeleaf;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class WebappThymeleafApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(WebappThymeleafApplication.class, args);
        }
    }
    

    @SpringBootApplication is a convenience annotation that adds all of the following:

    • @Configuration tags the class as a source of bean definitions for the application context.

      @Configuration将类标记为应用程序上下文的Bean定义的源

    • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

      @EnableAutoConfiguration告诉Spring Boot根据类路径设置,其它bean和各种属性设置开始添加bean

    • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

      通常,您会为Spring MVC应用添加@EnableWebMvc,但是当Spring Boot在类路径上看到spring-webmvc时,它将自动添加它。这会将应用程序标记为Web应用程序,并激活诸如设置DispatcherServlet之类的关键行为

    • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

      @ComponentScan告诉Spring在hello包中寻找其它组件,配置和服务,从而使其能够找到控制器

    The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.

    main()方法使用Spring Boot的SpringApplication.run()方法启动应用程序。您是否注意到没有一行XML?也没有web.xml文件。该网络应用程序是100%纯Java,因此您无需配置任何管道或基础架构

    6. Create a JPA Entity called User.java

    package com.guides.webappthymeleaf.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. Create Spring Data JPA Repository - UserRepository.java

    package com.guides.webappthymeleaf.repositories;
    
    import com.guides.webappthymeleaf.domain.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User, Integer> {
    
    }
    

    8. Create Spring Controller - HomeController.java

    package com.guides.webappthymeleaf.controllers;
    
    import com.guides.webappthymeleaf.repositories.UserRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HomeController {
    
        @Autowired
        UserRepository userRepository;
    
        @RequestMapping("/")
        public String home(Model model) {
            model.addAttribute("users", userRepository.findAll());
            return "index";
        }
    }
    

    9. Configuring MySQL Database

    Configure application.properties to connect to your MySQL database. Let's open an application.properties file and add the following database configuration to it.

    配置application.properties以连接到您的MySQL数据库。打开application.properties文件,并向其中添加以下数据库配置

    logging.level.org.springframework=INFO
    
    # Datasource Configuration
    spring.datasource.url=jdbc:mysql://localhost:3306/users_database?CreateDatabaseIfNotExist=true&sslMode=DISABLED&serverTimezone=UTC&useLegacyDatetimeCode=false
    spring.datasource.username=root
    spring.datasource.password=MyNewPass4!
    
    # Hibernate Configuration
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
    

    message.properties

    Create a message.properties under resource folder and add the following content to it -

    在资源文件夹下创建一个message.properties,并添加以下内容-

    app.title=SpringMVC JPA Demo (With SpringBoot)
    

    10. Insert SQL Script

    Once you will run this application will create users table in a database and use below insert SQL script to populate a few records in a users table.

    运行该应用程序后,将在数据库中创建用户表并在下面使用插入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. Create a Thymeleaf View - index.html

    Let's create a Thymeleaf view to show the list of users. Locate index.html file under src/main/resources/templates folder of this project.

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

    <!DOCTYPE html>
    <html lang="en">
    <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. Running the Application

    Now run Springboot2WebappThymeleafApplication.java as a Java application and point your browser to http://localhost:8080/.

    13. Source code on GitHub

    Spring Boot 2 MVC Web Application Thymeleaf JPA MySQL Example

  • 相关阅读:
    21天搞定聊天机器人之{命名实体识别}
    e到底是什么?
    An example of using Pandas for regression
    Time-Series Analysis
    Multiple Regression
    Regression Analysis Using Excel
    Correlation and Regression
    Hypothesis Testing
    Sampling and Estimation
    Common Probability Distributions
  • 原文地址:https://www.cnblogs.com/PrimerPlus/p/13391622.html
Copyright © 2020-2023  润新知