1.项目创建
目前idea中已无java8版本的快捷创建方式了,所以我们换一个创建方式
访问https://start.aliyun.com/
2.项目结构配置
common下的代码可以忽略
1.UserController
package com.hengbao.demo2.controller;
import com.hengbao.demo2.entity.User;
import com.hengbao.demo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
@Controller
public class UserController {
@Autowired
private UserService userService;
//控制跳转到index页面
@GetMapping("/index.html")
public String checkAll(Map<String, List> result){
List list=userService.findAll();
result.put("list",list);
return "html/index";
}
//控制跳转到add页面
@GetMapping("/add.html")
public String addHtml(Map<String, List> result){
List list=userService.findAll();
result.put("list",list);
return "html/add";
}
//新增接口,并控制返回到首页
@PostMapping("/add")
public String addIt(User user){
userService.addUser(user);
return "redirect:/index.html";
}
//删除接口,并控制回到首页
@RequestMapping("/delete/{id}")
public String delete(@PathVariable Integer id, HttpServletResponse servletResponse){
userService.deleteUser(id);
System.out.println("delete方法执行");
return "redirect:/index.html";
}
//查询单个数据接口,并控制回到修改页面
@GetMapping("/query/{id}")
public String updatePage(Model model, @PathVariable int id){
User users = userService.queryById(id);
model.addAttribute("list",users);
//表示跳转到modifie,html界面
return "html/modifie";
}
//更新数据接口,并控制返回首页
@RequestMapping("/update")
public String updateUser(Model model,User user,HttpServletRequest request) {
String id = request.getParameter("id");
User userById = userService.queryById(Integer.parseInt(id));
userService.updateUser(user);
System.out.println(user);
return "redirect:index.html";
}
}
2.User
package com.hengbao.demo2.entity;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private long id;
private String name;
private int age;
private String jia;
}
3.UserService
package com.hengbao.demo2.service;
import com.hengbao.demo2.entity.User;
import java.util.List;
public interface UserService {
List<User> findAll();
User queryById(int id);
int addUser(User user);
int deleteUser(int id);
int updateUser(User user);
}
4.UserServiceImpl
package com.hengbao.demo2.service.impl;
import com.hengbao.demo2.entity.User;
import com.hengbao.demo2.mapper.UserMapper;
import com.hengbao.demo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
public UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public User queryById(int id) {
return userMapper.queryById(id);
}
@Override
public int addUser(User user) {
return userMapper.addUser(user);
}
@Override
public int deleteUser(int id) {
return userMapper.deleteUser(id);
}
@Override
public int updateUser(User user) {
return userMapper.updateUser(user);
}
}
5.UserMapper
package com.hengbao.demo2.mapper;
import com.hengbao.demo2.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from student")
public List<User> findAll();
@Select("select * from student where id=#{id}")
public User queryById(int id);
@Insert("insert into student(name,age,jia) values(#{name},#{age},#{jia})")
public int addUser(User user);
@Delete("delete from student where id=#{id}")
public int deleteUser(int id);
@Update("update student set name=#{name},age=#{age},jia=#{jia} where id=#{id}")
public int updateUser(User user);
}
6.add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div style="width:600px;height:100%;margin-left:270px;">
<form action="/add" method="post">
<!-- form-control给input添加这个class后就会使用bootstrap自带的input框-->
姓名:<input class="form-control" type="text" th:value="${name}" name="name"><br>
<!--注意参数的拼接-->
年龄:<input class="form-control" type="text" th:value="${age}" name="age"><br>
家乡:<input class="form-control" type="text" th:value="${jia}" name="jia"><br>
<button class="btn btn-primary btn-lg btn-block">保存</button>
</form>
</div>
</body>
</html>
7.index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<style>
a{
color: #ffffff;
}
h1{
/*文字对齐*/
text-align: center;
}
</style>
<body>
<h1>spring-boot</h1>
<!--table-striped:斑马线格式,table-bordered:带边框的表格,table-hover:鼠标悬停高亮的表格-->
<table class="table table-striped table-bordered table-hover text-center">
<thead>
<tr style="text-align:center">
<!-- th标签定义html表格中的表头单元格-->
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>家乡</th>
<th>操作</th>
</tr>
</thead>
<!--tr标签定义html表格中的所有行-->
<!-- 遍历集合,如果被遍历的变量users为null或者不存在,则不会进行遍历,也不会报错-->
<tr th:each="list:${list}">
<!-- td标签定义html表格中的标准单元格-->
<td th:text="${list.id}"></td>
<td th:text="${list.name}"></td>
<td th:text="${list.age}"></td>
<td th:text="${list.jia}"></td>
<td>
<!-- a标签用来定义超链接 href表示超链接-->
<a class="btn btn-primary" th:href="@{'/query/'+${list.id}}">更改</a>
<a class="btn btn-danger" th:href="@{'/delete/'+${list.id}}">删除</a>
</td>
</tr>
</table>
<button class="btn btn-block" ><a href="add.html">添加用户</a></button>
</body>
</html>
8.modifie.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改用户</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div style="width:600px;height:100%;margin-left:270px;">
<form action="/update" method="post">
<!-- rest风格中的更新是put请求,
所以这块先使用post请求,然后隐藏起来改为put请求-->
<input name="_method" type="hidden" value="put">
ID:<input class="form-control" type="text" th:value="${list.id}" name="id"><br>
姓名:<input class="form-control" type="text" th:value="${list.name}" name="name"><br>
年龄:<input class="form-control" type="text" th:value="${list.age}" name="age"><br>
家乡:<input class="form-control" type="text" th:value="${list.jia}" name="jia"><br>
<button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
</form>
</div>
</body>
</html>
9.application.properties
#ä¸é¢è¿äºå
容æ¯ä¸ºäºè®©MyBatisæ å°
#æå®MybatisçMapperæä»¶
mybatis.mapper-locations=classpath:mappers/*xml
#æå®Mybatisçå®ä½ç®å½
mybatis.type-aliases-package=com.hengbao.demo2.mybatis.entity
# THYMELEAF (ThymeleafAutoConfiguration)
# å¼å¯æ¨¡æ¿ç¼åï¼é»è®¤å¼ï¼ true ï¼
spring.thymeleaf.cache=true
# æ£æ¥æ¨¡æ¿æ¯å¦åå¨ï¼ç¶åååç°
spring.thymeleaf.check-template=true
# æ£æ¥æ¨¡æ¿ä½ç½®æ¯å¦æ£ç¡®ï¼é»è®¤å¼ :true ï¼
spring.thymeleaf.check-template-location=true
#Content-Type çå¼ï¼é»è®¤å¼ï¼ text/html ï¼
spring.thymeleaf.content-type=text/html
# å¼å¯ MVC Thymeleaf è§å¾è§£æï¼é»è®¤å¼ï¼ true ï¼
spring.thymeleaf.enabled=true
# 模æ¿ç¼ç
spring.thymeleaf.encoding=UTF-8
# è¦è¢«æé¤å¨è§£æä¹å¤çè§å¾åç§°å表ï¼â½¤éå·åé
spring.thymeleaf.excluded-view-names=
# è¦è¿â½¤äºæ¨¡æ¿ä¹ä¸çæ¨¡æ¿æ¨¡å¼ãå¦â»
StandardTemplate-ModeHandlers( é»è®¤å¼ï¼ HTML5)
spring.thymeleaf.mode=HTML5
# å¨æå»º URL æ¶æ·»å å°è§å¾åç§°åçåç¼ï¼é»è®¤å¼ï¼ classpath:/templates/ ï¼
spring.thymeleaf.prefix=classpath:/templates/
# å¨æå»º URL æ¶æ·»å å°è§å¾åç§°åçåç¼ï¼é»è®¤å¼ï¼ .html ï¼
spring.thymeleaf.suffix=.html
# åºç¨æå¡ WEB 访é®ç«¯å£
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/web_service?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=你的用户名
spring.datasource.password=你的密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.configuration.log-impl=org.apache.ibatis.logging.slf4j.Slf4jImpl
10.pom.xml
<?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>
<groupId>com.hengbao</groupId>
<artifactId>demo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo2</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</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.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.hengbao.demo2.Demo2Application</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
11.数据库sql
CREATE TABLE `student` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`age` INT(11) NULL DEFAULT NULL,
`jia` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
3.运行项目
通过maven导入项目依赖
启动项目
项目页面
=========================================================================
自此你已成功创建第一个springboot项目实现了简单的增删改查
闲聊一句,我当年上学时对我要做的这些非常不了解并且很混乱,其实我们做这些只是为了将数据的操作可视化和展示给大家去看,毕竟直接操作sql还是比较麻烦的,然后Spring Boot + Thymeleaf(前端渲染模板)不是前后端分离架构,页面加载时,服务器直接返回渲染好的完整 HTML 页面(这点你们看代码中 )
userService.addUser(user);
return "redirect:/index.html";
也能发现,其实是直接把前端页面+数据返回了回来,这种和你们学的JSP有点相似,后续我会再将前后端分离架构的项目也拿一个出来给大家看看(Vue + Spring Boot)