springboot+gradle+thymeleaf项目开发入门

第一个springboot项目

使用eclipse和gradle构建第一个springboot项目。

1环境搭建

Java生态体系中有三大构建工具:Ant、Maven和Gradle。Ant几乎销声匿迹,Maven由于较为不灵活的配置也渐渐被遗忘,而由于Gradle是基于Ant和Maven的一个优化版本,变得如日中天。

1、安装gradle:

第1步:获取gradle

官网下载gradle: https://gradle.org/releases/    //我下载的是v6.4

第2步:解压

解压到如下目录:F:\qianduan\gradle-6.4.1

第3步:配置环境变量

在系统变量中添加:

变量名:GRADLE_HOME

变量值:F:\qianduan\gradle-6.4.1

path中缀加:%GRADLE_HOME%\bin

 

测试:启动cmd命令行

输入gradle或gradle –v

输出gradle的相关版本等信息,说明gradle配置成功。

2 创建gradle项目

1、eclipse安装插件

通过eclipse创建gradle项目:   //我的eclipse自带了gradle插件。

1:安装gradle插件

 http://download.eclipse.org/buildship/updates/e46/reases/2.x

help à install new softwareà输入上述地址,安装.

2:eclipse配置gradle

window-》preference—》gradle,选择自己本机安装的gradle

local installation directory:F:\qianduan\gradle-6.4.1

gradle user home:C:\Users\he\.gradle

2、创建springboot项目 

通过Spring Inutializr初始化

1:生成: https://start.spring.io/

2:通过指令编译-运行(方法1

从命令行进入到项目的根目录F:\qianduan\wordspace\hello

执行gradle build

运行:生成一个build目录,进去找到jar文件

java  –jar  build/libs/….jar   //运行我们的项目

如果想结束项目,直接ctrl+c即可停止。

3:在eclipse中运行(方法2

导入:打开eclipse,导入gradle项目,选中项目导入。

更新依赖:右键项目名—》gradle—》refresh gradle project

编译运行:右键Application.java—》run as—》java application

测试:打开google浏览器:输入localhost:8080 会出现一个错误页面

grails springboot 版本 springboot和gradle教程_java

 

到此,springboot项目运行成功。

项目目录简介:

resourses:放静态资源

   /static:放js、css

   /templates 默认放页面的路径

/application.properties:配置页面路径、访问数据库信息

src :存放代码

build.gradle:类似于maven的pom.xml

3 核心代码

目标:实现用户管理的增删改查功能,学会使用springboot开发项目。

配置文件

mysq中创建user表:  //现在mysql数据库中创建user表

user表:

id:int
name:varchar(255)
email:varchar(255)
参考sql代码:
create table user(
id int primary key, 
name varchar(255),
email varchar(255)  )

 

build.gradle代码如下:

//本身需要的插件
plugins {
   id 'org.springframework.boot' version '2.3.0.RELEASE'
   id 'io.spring.dependency-management' version '1.0.9.RELEASE'
   id 'java'
}
group = 'com.scitc'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
//指定仓库
repositories {
   //mavenCentral()
   mavenLocal()
   maven{
       url 'http://maven.aliyun.com/nexus/content/groups/public/'
   }
}
//依赖
dependencies {
   implementation 'org.springframework.boot:spring-boot-starter-web'
   testImplementation('org.springframework.boot:spring-boot-starter-test') {
      exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
   }
   compile('org.springframework.boot:spring-boot-starter-thymeleaf')
   //spring  data jpa的依赖
   compile('org.springframework.boot:spring-boot-starter-data-jpa')
        //mysql连接驱动的依赖
   compile('mysql:mysql-connector-java:6.0.5')
   //添加jquery依赖
   compile group: 'org.webjars.bower', name: 'jquery', version: '3.3.0'
   //添加bootstrap依赖
   compile group: 'org.webjars', name: 'bootstrap', version: '4.1.0'
}
test {
   useJUnitPlatform()
}
application.properties
# 这个是配置模板路径的,默认就是templates,可不用配置
#spring.thymeleaf.prefix=classpath:/templates/
# 这个可以不配置,检查模板位置
#spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.content-type=text/html
spring.thymeleaf.encoding=UTF-8
#热部署静态文件
spring.thymeleaf.cache=false
#使用html5
spring.thymeleaf.mode=HTML5
#DataSource
spring.datasource.url=jdbc:mysql://localhost/blog?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#jpa
spring.jpa.show-sql = true
#spring.jpa.hibernate.ddl-auto=create-drop

domain层

User.java
package com.scitc.mytest.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import ;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
 
@Entity
@XmlRootElement  //MediaType 转为 XML
@Table
public class User implements Serializable{
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;//实体唯一的标识
   @Column(nullable = false)
    private String name;
   @Column(nullable = false)
    private String email;
   public User() {
   }
   public User(Long id,String name,String email) {
      this.id = id;
       = name;
      this.email = email;
   }
     public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
       = name;
   }
   public String getEmail() {
      return email;
   }
   public void setEmail(String email) {
      this.email = email;
   }
   @Override
   public String toString() {
      return String.format("User[id=%d, name='%s', age='%d']",
                id, name, email);
   }
}

UserRepository层

接口UserRepository.java
package com.scitc.mytest.repository;
import org.springframework.data.repository.CrudRepository;
import com.scitc.mytest.domain.User;
public interface UserRepository extends CrudRepository<User, Long> {
}
controller层
UserController.java
package com.scitc.mytest.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.scitc.mytest.domain.User;
import com.scitc.mytest.repository.UserRepository;
 
@RestController 
@RequestMapping("/users")
public class UserController {
   @Autowired
   private UserRepository userRepository;
   /*
    * 从用户仓库中获取用户列表
    * */
   private List<User> getUserlist(){
      List<User> users = new ArrayList<>();
      for(User user : userRepository.findAll()) {
         users.add(user);
      }    
      return users;
   }
   /**
    * 查询所有用户,数据封装到模型中,返回视图模型对象
    * @param model
    * */
   //get方法获取用户列表
   @GetMapping
   private ModelAndView list(Model model) {
      model.addAttribute("userList", getUserlist());
      model.addAttribute("title", "用户管理");
      return new ModelAndView("users/list","userModel",model);
   }
   /**
    * 根据id查询用户详细信息
    */
   @GetMapping("{id}")
   public ModelAndView view(@PathVariable("id") Long id,Model model){
      Optional<User> user = userRepository.findById(id);
      model.addAttribute("user", user.get());
      model.addAttribute("title", "查看用户");
      return new ModelAndView("users/view","userModel",model);
   }
   /**
    *修改页面
    *获取表单页面 ,自动把表单的数据填充到new User对象中
    *userModel:是视图模型的名字,在页面可以获取到
    */
   @GetMapping("/form")
   public ModelAndView createForm(Model model){
      model.addAttribute("user", new User());
      model.addAttribute("title", "查看用户");
      return new ModelAndView("users/form","userModel",model);
   }
   /**
    * 新建用户
    * @param user
    * @param result
    * @param redirect
    * @return
    * 根节点就是users,所以下面注解映射的路径不用填
    */
   @PostMapping
   public ModelAndView create(User user) {
      user = userRepository.save(user);
      return new ModelAndView("redirect:/users");
   }
   /**
    * 删除用户
    * @param id
    * @return
    */
   @GetMapping(value = "delete/{id}")
   public ModelAndView delete(@PathVariable("id") Long id, Model model) {
      userRepository.deleteById(id);;
      model.addAttribute("userList", getUserlist());
      model.addAttribute("title", "删除用户");
      return new ModelAndView("redirect:/users");
      //return new ModelAndView("users/list", "userModel", model);
   }
   /**
    * 修改用户
    * @param user
    * @return
    */
   @GetMapping(value = "modify/{id}")
   public ModelAndView modifyForm(@PathVariable("id") Long id, Model model) {
      Optional<User> user = userRepository.findById(id);
      model.addAttribute("user", user.get());
      model.addAttribute("title", "修改用户");
      return new ModelAndView("users/form", "userModel", model);
   }
}
页面
templates/fragments下:
header.html
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Thymeleaf
</head>
<body>
   <div th:fragment="header">
Thymeleaf
      <a href="/users" th:href="@{~/users}">首页</a>
   </div>
</body>
</html>
footer.html
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Thymeleaf
</head>
<body>
   <div th:fragment="footer">
     <a href="#">欢迎来到我的主页!</a></div>
</body>
</html>
templates/users下:
list.html-显示用户页面
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
 <title th:text="${userModel.title}">welcome</title>
</head>
<body>
   <div th:replace="fragments/header::header"></div>
   <h3 th:text="${userModel.title}">Welcome to </h3>
    <table border="1">
      <thead>
        <tr>
           <td>ID</td>
           <td>name</td>
           <td>email</td>
        </tr>
      </thead>
      <tr th:if="${userModel.userList.size()} eq 0">
        <td colspan="3">没有用户信息!!</td>
    </tr>
      <tr th:each="user:${userModel.userList}">
          <td th:text="${user.id}">id</td>
           <td th:text="${user.email}">email</td>
           <td><a href="view.html" th:href="@{'/users/' + ${user.id}}"
               th:text="${}">he</a></td>
      </tr>
    </table>
   <div th:replace="fragments/footer::footer"></div>
</body>
</html>
view.html-展示单个用户信息
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">users : View</title>
</head>
<body>
      <div th:replace="fragments/header::header"></div>
      <h3 th:text="${userModel.title}">Welcome to </h3>
     <div>
    <a href="/users">返回主页</a>
      </div>
       <div>
    <p><strong>ID:</strong><span id="id" th:text="${}">123</span></p>
    <p><strong>Name:</strong><span id="name" th:text="${userModel.}">he</span></p>
    <p><strong>Email:</strong><span id="age" th:text="${userModel.user.email}">30</span></p>
</div>
     <div>
       <a th:href="@{'/users/delete/'+${}}">删除</a>
       <a th:href="@{'/users/modify/'+${}}">修改</a>
     </div>
   <div th:replace="fragments/footer::footer"></div>
</body>
</html>
form.html-修改用户页面
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>修改页面</title>
</head>
<body>
   <div th:replace="fragments/header::header"></div>
      <h3 th:text="${userModel.title}">Welcome to </h3>
     <form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">
      <input type="hidden" name="id" th:value="*{id}"> 名称:<br> <!-- eq
      <input type="text" name="name" th:value="*{name}"> <br>
      邮箱:<br> <input type="text" name="email" th:value="*{email}">
      <input type="submit" value="提交">
   </form>
   <div th:replace="fragments/footer::footer"></div>
</body>
</html>

附件

mavenCentral寻找依赖插件

https://search.maven.org/

https://mvnrepository.com/

 

参考文献:

 //gradle配置文件解析

  //常用注解

  //自定义查询